ajax form submits blank description to only first ids - javascript

I have below code for submitting the form with ajax but only first instances out of 5 comment box are being submitted for balance I am getting discription=" and also being inserted to the wrong id. here is my code and live example. I want to allow users to comment on any items
http://way2enjoy.com/app/jokestest-991-1.php
$output .='<div id="'.$idd.'" align="left" class="messagelove_box" ><div class="content_box_1">
<div class="content_box_2z"><sup class="joke_icon"></sup></div>
<div class="content_box_3_title"></div>
<div class="content_box_3_text">'.nl2br($cont).'</div>
<script type="text/javascript">
var ajaxSubmit = function(formEl) {
var url = $(formEl).attr(\'action\');
var comment=document.getElementById("jokes_comment").value;
var joke_id=document.getElementById("joke_id_hidden'. $idd.'").value;
$.ajax({
url: url,
data:{
\'action\':\'addComment\',
\'comment\':comment,
\'joke_id\':joke_id
},
dataType: \'json\',
type:\'POST\',
success: function(result) {
console.log(result);
$.ajax({
url: url,
data:{
\'action\':\'getLastComment\',
\'joke_id\':joke_id
},
dataType: \'json\',
type:\'POST\',
success: function(result) {
$(\'#jokes_comment\').val("");
console.log(result[0].description);
$("#header ul").append(\'<li>\'+result[0].description+\'</li>\');
},
error: function(){
alert(\'failure\');
}
});
},
error: function(){
alert(\'failure\');
}
});
return false;
}
</script>
<div id="header" class="content_box_31_text"><ul id="commentlist" class="justList">'.$contpp.'</ul></div>
<form method="post" action="check/process2.php" class="button-1" onSubmit="return ajaxSubmit(this);"><input type="hidden" value="'. $idd.'" id="joke_id_hidden'. $idd.'"><input type="text" id="jokes_comment" value="" name="jokes_comment">
<input type="submit" value="comment"></form>
</div></div>
';

The code posted doesn't tell the full story, but looking at the URL mentioned does. The snippet you've posted is being repeated over and over again, identically in the page. That means that each definition of the ajaxSubmit function overwrites the previous one, and that you have multiple input elements all with the same id. No wonder the page is confused as to what to do. You only need one submit function, if it's written properly it can handle all the different comment inputs. And your comment inputs can't have the same id each time, but they can have the same CSS class, and since they are all within the form, when we submit a specific form, we know the context we are working in, and jQuery can automatically find all the fields in the form for us, without us having to write code to access them all individually.
So..with that design in mind, define your javascript like this, and make sure it only gets rendered once in your entire page output. I've re-written it slightly to take advantage of the easier syntax provided by jQuery.
$(".comment-form").submit(function(event) {
event.preventDefault(); //prevent the default postback behaviour
var form = $(this);
var jokeID = form.find(".joke_id").val();
$.ajax({
url: form.attr("action"),
type: "POST",
dataType: "json",
data: $(this).serialize(), //automatically finds all the form fields and puts the data in postback-friendly format
success: function(result) {
//I'm not convinced you need this second ajax call - can't you just write the contents of the input box directly into the list? But I'll leave it here in case you want it
$.ajax({
url: form.attr("action"),
type: "POST",
dataType: "json",
data:{
"action":"getLastComment",
"joke_id": jokeID
},
success: function(result) {
form.find(".jokes_comment").val("");
$("#header-" + jokeID + " ul").append("<li>" + result[0].description + "</li>");
},
error: function (jQXHR, textStatus, errorThrown) { //this is the correct definition of the error function as per jQuery docs
alert("An error occurred while contacting the server: " + jQXHR.status + " " + jQXHR.responseText + ".");
}
});
},
error: function (jQXHR, textStatus, errorThrown) { //this is the correct definition of the error function as per jQuery docs
alert("An error occurred while contacting the server: " + jQXHR.status + " " + jQXHR.responseText + ".");
}
});
});
Secondly, make the PHP that generates the comment markup for each joke look like this:
<div id="header-'.$idd.'" class="content_box_31_text">
<ul id="commentlist" class="justList">'.$contpp.'</ul>
</div>
<form method="post" action="check/process2.php" class="button-1 comment-form">
<input type="hidden" value="'. $idd.'" name="joke_id"/>
<input type="hidden" value="addComment" name="action" />
<input type="text" class="jokes_comment" value="" name="comment" />
<input type="submit" value="comment">
</form>

Related

laravel ajax unexpected end of json input

Hello guys i am desperate i am not getting completly this syntax / concept of Ajax.
I have 2 forms on my page. Based on the value of the hidden field a certain logic in my controller will be executed. Its simple actually -- i thought. I am trying to pass an array from my ajax to my controller and then passing it back to my view. I know it doesnt make much sense. But i am trying to understand how that works. The first logic gets executed but the other one gets me this error:
jqXHR is : [object Object] textStatus is : parsererror errorThrown is : SyntaxError: Unexpected end of JSON input
Why is that ? Can you guys please give me an advice.
Update
I tried not to put the whole code and just reduce it to the main question. But since it caused confusion of the rootcause i will show the whole code of the parts which might be relevant. I edited the question to the below.
BLADE
<center>
<div class="col-md-12">
<h3>xlsx, xls, ods, csv to Text</h3>
<form id="xlsForm" enctype="multipart/form-data">
#csrf
<input type="file" name="excelfile" />
<input name ="loadSubmit" id="loadSubmit" type="submit"/>
<input type ="hidden" name="load" value="0">
</form>
</div>
</center>
<div class ="row">
<div class ="col-md-3">
<div class="container mt-5">
<h2 id="words" class="mb-4">Skills found</h2>
</div>
<form id="xlsFormUpdate" enctype="multipart/form-data">
<input type ="hidden" name="load" value="1">
<div id="inner">
</div>
<input name ="updateSubmit" id="updateSubmit" type="submit"/>
</form>
</div>
<div class ="col-md-9">
#include('layouts.partials.datatable')
</div>
</div>
Controller:
if ($request->input('load') == '0') {
//some code -- this works fine
return response()->json($data); //This data can be send - no problem
} elseif (($request->input('load') == '1')) {
$data = $request->post('checkbox_array');
return response->json($data); // i tried json_encode too .. not working.
}
Jquery code
$(document).ready(function(){
$('#xlsForm').submit(function uploadFile(event){
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success:function (response) {
$("#inner").empty();
$.each(response,function(index,value){
$("#inner").append
('<div class="row">' +
'<div class="col-xs-2">'+
'<input type="checkbox" class="'+value+'" value="'+value+'" name="checkbox[]" checked > <label style="font-weight: bold" for="skillChoice_'+index+'">'+value+' </label>' +
'</div>'+
'<div class="col-xs-1">'+
'<input class="'+value+'" type="number" name="weight[]" min="1" max="3" value="1"> '+
'</div>'+
'</div>');
});
}
});
});
$('#xlsFormUpdate').submit(function uploadFile(event) {
event.preventDefault();
var checkbox_array = [];
$('input[type=checkbox]').each(function (index,value) {
if (this.checked)
{
checkbox_array.push(1);
}
else {
checkbox_array.push(0);
}
});
let checkbox_s = JSON.stringify(checkbox_array)
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: "POST",
data: {checkbox_array:checkbox_s},
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function (response) {
alert('The Response is ' + response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('jqXHR is : ' + jqXHR
+ 'textStatus is : ' + textStatus
+ ' errorThrown is : ' + errorThrown);
},
})
});
});
When using ajax submit event to send data to controller, the data in the field data: {checkbox_array:checkbox_s}, will be send to the controller. Since the input field load was never sent, the elseif (($request->input('load') == '1')) clause was never true and the controller was never going into that section and was never returning the right response. The data had to be changed like this var my_datas JSON.stringify({mydata:checkbox_array, load: "1"}); and then in ajax the data could be send like data:my_datas. In controller the field load can then be processed.

Can't get AJAX and PHP working

So here is the scenario:
I have HTML, JS, and PHP Files. Within the PHP File is an associative array of default values to fill out various form elements on the HTML file. I am attempting to use AJAX to take the files from the PHP Files, and put them in the corresponding form elements. However nothing is working.....
Below is the code for the corresponding files. Any help figuring this out is greatly appreciated :)
HTML
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
PHP
<?php
// Return JSON default data if requested
if ($_REQUEST['act'] == 'default')
{
$defaultData = array('name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street");
echo json_encode($defaultData);
}
?>
JAVASCRIPT
$(document).ready(function()
{
$("#InsertDefault").click(function()
{
// make an AJAX call here, and place results into the form
$.post('backend.phps',
{ act: 'default' },
function(data) {
for (var key in data) {
document.getElementById(key).value = data[key] }
},
'json');
// prevents link click default behaviour
return false;
});
});
As a side note, I always have trouble with web development stuff because I have no idea how to properly debug what I am doing. If anyone has any tips on what are some useful tricks/tools to use for debugging web code, I'd be more than happy to get some input on that too.
Thanks for your time.
For ajax code request use:
$("#InsertDefault").click(function(){
$.ajax({
type: "POST",
url: "backend.phps",
data: "act=default&name=test&phone=test", //Something like this
success: funtion(msg){
console.log(msg);
},
beforeSend:function(dd){
console.log(dd)
}
});
});
and in your backend.php file
if ($_REQUEST['act'] == 'default'){
//echo $_REQUEST['name'];
}
And for simple debugging use browsers' console, right click on the page and click Inspect Element. (Simple)
You can also install Firebug extension on Mozilla Firefox and then right click on the page and click on inspect Element with firebug. after this click on the Console tab there.
These are the basic and simple debugging for simple ajax request.
Per the newest Ajax documentation your ajax should include the Success and Failure callbacks where you can handle the response being sent from your PHP.
This should work with you existing PHP file.
Ajax
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#InsertDefault', function (event) {
$.ajax({
url: "/backend.phps",
type: 'POST',
cache: false,
data: {act: 'default'},
dataType: 'json',
success: function (output, text, error)
{
for (var key in output.defaultData) {
document.getElementById(key).value = data[key]
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
preventDefault(event);
});

Validate automatically on button press

Hi I am using JQuery Form validator to validate a form, and using knockout js to call a function using a button, What I want is that when the button is clicked the the knockout js function should be called, and also at the same time check if all the fields are validated if not, it should just do nothing till all the fields are validated.
Link for the jquery validator form http://www.formvalidator.net/#advanced_programmatically
Here is a field and the button that calls the function.
<input type="text" name="birthday" data-validation="date" data-validation-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" data-validation-help="You must be more than 20 years old" class="form-control" value="<?php if (isset($user['Birthday'])) {echo $user['Birthday'];} ?>">
<div data-bind="ifnot: (loggedIn() == 'true')">
<button data-bind="click : openUpTwoStepAuth " type="submit" id="openUpTwoStepAuth" class="btn registerbtn">
<?php echo lang("register_continue_btn"); ?>
</button>
</div>
And here is the knockout js function that tries to call the validation as soon as the button is clicked, but in my case it does not check the validation and goes on with the ajax call.
self.openUpTwoStepAuth = function(){
$('#openUpTwoStepAuth').validate(function(valid, elem) {
if(!valid){
return;
}
});
self.emailtokenconfirmation(false);
self.tokenError(null);
self.showTwoStepAuth();
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/sendEmailForTwoStepAuth/',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON({customerEmail : self.customerEmail()})
})
.done(function(data) {
if(data.success){
self.emailtokenconfirmation(true);
}else{
self.tokenError(data.result);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error code thrown: " + errorThrown);
})
.always(function(data){
});
}
It works fine if its just a normal button calling the submit function with this piece of code
<script>
$.validate({
modules : 'toggleDisabled',
disabledFormFilter : 'form.toggle-disabled',
showErrorDialogs : false
});
</script>
but for me I want to call a js function and at the same time check the validation of the field.
This seems to be already answered here
Knockout + Jquery Validate
Use submitHandler in validate to call your view model function on successful validation.

why AJAX redirects to the new page in PHP

I have a form:
<form class="searchForm">
<div class="box_style_1">
<h4><?= Yii::t("common", "Age"); ?></h4>
<?
echo '<b class="badge">3</b> ' . Slider::widget([
'name'=>'age',
'value'=>'250,650',
'sliderColor'=>Slider::TYPE_GREY,
'pluginOptions'=>[
'min'=>3,
'max'=>21,
'step'=>1,
'range'=>true
],
]) . ' <b class="badge">21</b>';
?>
<br /><br />
<input type="submit" value="Search" class="searchByAge"/>
<br /><br />
</div>
</form>
And want to show the result in console.log:
$('.searchByAge').on('click', function(e){
e.preventDefault();
var range = $('.form-control').val();
var min = range.split(',')[0];
var max = range.split(',')[1];
//alert(min+' '+max);
$.ajax({
type: 'POST',
url: '/age/'+min+'/'+max,
data: $('.searchForm').serialize(),
success: function (data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
})
and that's my AJAX code. But when I click on Search button it redirects me to the new page and nothing in the console log. I do not know what is wrong in my code.
I return a JSON from the '/age/min_age/max_age' page, but the result shows in the new page.
How can I fix this problem?
change code to below. change input type submit to button
<input type="button" value="Search" class="searchByAge"/>
also wrap your code in $(document).ready();
Make sure to add jQuery library from correct path.
$(document).ready(function(){
$('.searchByAge').on('click', function(e){
e.preventDefault();
var range = $('.form-control').val();
var min = range.split(',')[0];
var max = range.split(',')[1];
//alert(min+' '+max);
$.ajax({
type: 'POST',
url: '/age/'+min+'/'+max,
data: $('.searchForm').serialize(),
success: function (data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
});
});
replace your code
$('.searchByAge').on('click', function(e){
e.preventDefault();
with this
$('form.searchForm').on('submit', function(e){
e.preventDefault();
on first code you are preventing your click event instead of submit event thats why form is still submitting

I usually wait for a collection of asynchronous events to finish using a setInterval poller. Is there a better way? [duplicate]

Let me explain my code a little bit (Excuse me if somethings wrong, I've just written this example from scratch, it is very close to what I currently have).
HTML:
<form id="form">
<!-- Friend 1 -->
Name 1: <input type="text" name="friendName1" id="friendName1" class="friendName" value=""><br />
Email 1: <input type="text" name="friendEmail1" id="friendEmail1" value=""><br /><br />
<!-- Friend 2 -->
Name 2:<input type="text" name="friendName2" id="friendName2" class="friendName" value=""><br />
Email 2:<input type="text" name="friendEmail2" id="friendEmail2" value=""><br /><br />
<!-- Friend 3 -->
Name 3:<input type="text" name="friendName3" id="friendName3" class="friendName" value=""><br />
Email 3:<input type="text" name="friendEmail3" id="friendEmail3" value=""><br /><br />
<!-- Friend 4 -->
Name 4:<input type="text" name="friendName4" id="friendName4" class="friendName" value=""><br />
Email 4:<input type="text" name="friendEmail4" id="friendEmail4" value=""><br /><br />
<!-- Submit -->
<input name="submit" type="submit" value="Submit">
</form>
JS:
$("#form").submit(function(){
$(".friendName[value!='']").each(function(){
var idEmail = 'friendEmail' + $(this).attr("id").replace('friendName','');
if($("#"+idEmail+"[value!='']").length > 0){
var name = $(this).val();
var email = $("#"+idEmail).val();
// Submit the ajax request
$.ajax({
type: 'POST',
url: 'ajax/url',
data: {
name: name,
email: email
},
success: function(json) {
// Log a console entry if our ajax request was successful
console.log(name + " was submitted via ajax");
}
});
}
});
// Redirect the user to the thank you page
setTimeout( function() { window.location= '/thanks'; }, 2000 );
});
JSFiddle (redirect removed and ajax call replaced with console log for fiddle)
http://jsfiddle.net/cM5PX/
The HTML is a simple form, with friend name and friend email input fields.
The JS has an each function, which if the name and associated email have values, it runs an ajax call.
I need a way for these ajax calls to run (there could be 1 loop, there could be 15) and then after they have all finished, redirect to a new page.
The current way I'm doing it is horrible, as all of the ajax calls do not finish running before the page redirects.
What can I do to make this better? It needs to be fool proof and ONLY redirect once all of the ajax calls have finished (success or error, it doesn't matter - it just needs to redirect once its finished).
I have tried using async: false but it doesn't seem to make a difference.
I've thought about putting a counter in the each function and a counter in the ajax success function and if they both match, then do the redirect, but I am looking for some more experienced guidance.
Use deferred objects:
$("#form").submit(function(e){
e.preventDefault();
var calls = [];
$(".friendName[value!='']").each(function(){
// Submit the ajax request
calls.push($.ajax({
type: 'POST',
url: 'ajax/url',
data: {
name: name,
email: email
},
success: function(json) {
// Log a console entry if our ajax request was successful
console.log(name + " was submitted via ajax");
}
}));
});
$.when.apply($, calls).then(function() {
window.location= '/thanks';
});
});
Ok, this is fairly easy since you're using jQuery. jQuery comes with an integrated promise maker which also is wired up with jQuery's Ajax calls. What does that mean? Well, we can easily go like this:
var requests = [ ];
// ...
// Submit the ajax request
requests.push($.ajax({
type: 'POST',
url: 'ajax/url',
data: {
name: name,
email: email
},
success: function(json) {
// Log a console entry if our ajax request was successful
console.log(name + " was submitted via ajax");
}
}));
// at this point we filled our array with jXHR objects which also inherit the promise API
$.when.apply( null, requests ).done(function() {
document.location.href = '/thanks';
});
Note: The above code will only fire, if all requests completed successfully. If you need to handle the case if one ore more requested failed, use .then() or .fail() instead of .done(), too.
Just keep a counter of the AJAX calls and check to see when they have all completed.
Something like this:
$("#form").submit(function(){
var ajaxMax = $(".friendName[value!='']").length, ajaxCounter = 0;
$(".friendName[value!='']").each(function(){
var idEmail = 'friendEmail' + $(this).attr("id").replace('friendName','');
if($("#"+idEmail+"[value!='']").length > 0){
var name = $(this).val();
var email = $("#"+idEmail).val();
// Submit the ajax request
$.ajax({
type: 'POST',
url: 'ajax/url',
data: {
name: name,
email: email
},
success: function(json) {
// Log a console entry if our ajax request was successful
console.log(name + " was submitted via ajax");
if(++ajaxCounter >= ajaxMax)
window.location= '/thanks';
}
});
}
});
});
By default $.ajax is asynchronous. In the options hash being passed, add
async: false
That will serialize the calls you are making having it perform the way you want.
After getting comment from original poster, possible solution may be to do the following:
Inside the submit call determine the number of calls that should be made.
Store this result as a local variable within the handler function
Create a callback on 'complete:' that will examine the value of the calls
If the number of calls to be made is greater than 0, then decrement the value and return
If the number of calls reaches zero, update the window.location (really should use window.location.href as window.location is an object but browsers will allow this and perform correctly)
Note, I don't have any information on the thread safety of performing this kind of operation so YMMV.
Example Code:
$("#form").submit(function(eventObject){
var $ajaxFields= $(".friendName[value!='']").filter(function(index){
var idEmail = 'friendEmail' + $(this).attr("id").replace('friendName','');
return ($("#"+idEmail+"[value!='']").length > 0);
});
var numberToSubmit= $ajaxFields.length;
$ajaxFields.each(function(){
var idEmail = 'friendEmail' + $(this).attr("id").replace('friendName','');
var name = $(this).val();
var email = $("#"+idEmail).val();
// Submit the ajax request
$.ajax({
type: 'POST',
url: 'ajax/url',
data: {
name: name,
email: email
},
success: function(json) {
// Log a console entry if our ajax request was successful
console.log(name + " was submitted via ajax");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("call not completed: "+textStatus);
},
complete: function(jqXHR, textStatus) {
if( --numberToSubmit == 0 ) {
window.location.href= '/thanks';
}
}
});
});
// Prevent default form submission
return false;
});

Categories