JSON array not sent in AJAX request [duplicate] - javascript

What I want to do is send an JavaScript Array to a PHP file.
This is what I got:
var mydata = [];
console.log(document.getElementsByTagName("input")[0].name);
for (var i = 0; i < document.getElementsByTagName('input').length; i++) {
mydata[document.getElementsByTagName("input")[i].name] = document.getElementsByTagName("input")[i].value;
};
for (var i = 0; i < document.getElementsByTagName('select').length; i++) {
mydata[document.getElementsByTagName("select")[i].name] = document.getElementsByTagName("select")[i].value;
};
console.log(mydata);
$.ajax({
method: "POST",
url: "q.php",
data: {'lol': JSON.stringify(mydata)},
contentType: 'application/json',
dataType: 'json'
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
$('#debug').html(msg);
});
So as you can see, I create an array with a loop, at that moment all is fine. The problem is when I try to sent it through POST with JSON. I don't know if this is the best method...
I tried without JSON.stringify(); but the $_POST still empty
It seems like the post isn't sent, but I can see in the console the XHR post request has been sent.

Try to use this code and see the changes.
remove the
contentType: 'application/json',
dataType: 'json'
And change var mydata = [] into var mydata = {}
your ajax should look like this
$.ajax({
method: "POST",
url: "q.php",
data: {'lol': mydata}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
$('#debug').html(msg);
});
You dont have to stringify your mydata because you already decleared it as object.
Hope it helps

Related

Push/Add multiple JSON objects one by one to the API using ajax and for loop

I'm working on a code where I can push a JSON objects one by one inside an array going to the API using AJAX and for loop. The code here is just a rough sample of what I have been working on. I can't seem to make it work on in pushing the objects to the API JSON array
var lms_json = <?php echo json_encode($json_data); ?>;
var jobjects = JSON.parse(lms_json);
var data = jobjects[0];
for ( i = 0; i < jobjects.length; i++ ) {
var data = jobjects[i];
$.ajax({
type : 'POST',
url : url,
data : data,
dataType : 'json',
success : function() {
console.log(success);
},
error : function(error) {
console.log('Error')
}
})
}
You need to use JSON.stringify to serialize your JSON object. Also, specify the content-type to make the server expect JSON data. This might work:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
I think that your problem is that AJAX is asynchronous process so you can do the following to do it correctly:
var lms_json = <?php echo json_encode($json_data); ?>;
var jobjects = JSON.parse(lms_json);
var i=0;
function makeAjax(url, objs){
var data = objs[i];
i++;
$.ajax({
type : 'POST',
url : url,
data : data,
dataType : 'json',
success : function() {
console.log(success);
makeAjax();
},
error : function(error) {
console.log('Error')
}
})
}
makeAjax(url,jobjects);
So After every success callback run it will run the next. so it will be synchronous process.
I hope it helps.

JSON.parse : why this doesn't work

I got a JSON :
$.ajax({
type: "POST",
url: myUrl,
success: function (result) {
var data = JSON.parse(result);
for (var i = 0; i < data.poles.length; i++) {
....
What i see in debugger is that :
data = "{"poles":[{"id":36,"name":"AUVERGNE"},{"id":44,"name":"Alsace"},{"id":42,"name":"Artois"},....],"poleNumber":48}
But i get a message saying that data.poles is not defined
What do i miss?
Is Json ok?
{"poles":[{"id":36,"name":"AUVERGNE"},{"id":44,"name":"Alsace"},{"id":42,"name":"Artois"}],"poleNumber":48}
EDIT:
Ok, if you have this JSON:
data = {"poles":[{"id":36,"name":"AUVERGNE"},{"id":44,"name":"Alsace"},{"id":42,"name":"Artois"}],"poleNumber":48}
you can make data.poles perfectly. delete the first ", you have a wrong json, so you will never parse
"{"poles":[{"id":36,"name":"AUVERGNE"},{"id":44,"name":"Alsace"},{"id":42,"name":"Artois"}],"poleNumber":48}

How to post a form with ajax and return data in array?

HI how to post a form and return data it will be a array as like this
{
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
}
My code is this
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
var formValidate = $('#add-menu-list').parsley().validate();
validateFront();
// console.log(formValidate);
var menuName = $('input[data-api-attr=menuItemName]').val();
var validUntil = $('input[data-api-attr=validUntil]').val();
var menuStatus = $('input[data-api-attr=status]').val();
var menuNote = $('textarea[data-api-attr=notes]').val();
var menuDesc = $('textarea[data-api-attr=menuItemDesc]').val();
var dataString = {
menuItemName: menuName,
validUntil : validUntil,
status : menuStatus,
notes : menuNote,
menuItemDesc : menuDesc
};
if(formValidate == true){
alert('success');
console.log(menuName + validUntil + menuStatus + menuNote + menuDesc);
var url = "xyz.html"; // the script where you handle the form input.
$.ajax({
type: "POST",
// url: url,
dataType: "json",
data: $(dataString).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
}
});
}else{
alert('Validation fail ');
}
});
Since "data" is a server response i guess that your server return a json object. In this case you have to somehow inform the jquery's ajax that you expect a json response from server or you have to translate the "data" to a json object by your self.
It is best to follow the first option so you don t have to deal with the translation your self you can easily do that by giving an extra parameter tou your ajax reuest : dataType: 'json', this will do the trick!
Now that you have a proper response object from your request you can either stringify it with var string_resp=JSON.stringify(data); and then alert it alert(string_resp) or you can access its elements like that : alert(data.status) which will alert your object's status field etc.
so your code will be :
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(menuName).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // will alert an object
alert(data.status); // will alert object's status field in this case 1
alert(JSON.stringify(data)) // will alert the object as a string
}
});
you are sending only one value in serialize, serialize() should be on form element not on field element, like :
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
...
$.ajax({
...
data:$("#form").serialize();
...
success: function(data)
{
alert(data.notes); // show response
....
}
var myObj = {
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
};
myObj.toString = function()
{
var str = '';
for (var property in myObj)
{
if (myObj.hasOwnProperty(property) && (property != "toString") )
{
str += (property + ': ' + myObj[property] + "\n");
// do stuff
}
}
return str;
}
alert(myObj);

json couldn't change the dataWithLabels

Please can you help see the code. I would like to change the title name from 'Jason' to the temperature written in the JSON file.
var dataWithLabels = [
{
"title":"Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for(var i=0;i<1/*dataWithLabels.length*/;i++){
var statistic = data.current_observation;
dataWithLabels[i]['title']= statistic.temp_c;}}
//wanted to change Jason to the temperature written at the JSON file.Please help.
});
alert(dataWithLabels[0]['title']);
http://codepen.io/wtang2/pen/bEGQKP
It's NOT a duplicate, I am trying to replace the result from JSON file to title of dataWithLabels object
Since I don't know, if your JSON you are requesting is correct, I just assume it is. Still, if you like to see, what is happening in dataWithLabels after your Ajax-Request, you need to rewrite the function a little:
var dataWithLabels = [{
"title": "Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for (var i = 0; i < 1 /*dataWithLabels.length*/ ; i++) {
var statistic = data.current_observation;
dataWithLabels[i]['title'] = statistic.temp_c;
alert(dataWithLabels[i]['title']);
}
}
//wanted to change Jason to the temperature written at the JSON file.Please help.
});
Now, the status of dataWithLabels is alerted AFTER you insert the statistic.temp_c. Your code always alerts the state BEFORE the Ajax-request.
Hope that helps!
This is because AJAX request works asynchronously so you need to alert the result only after the AJAX request is completed for that you can do
var dataWithLabels = [{
"title": "Jason",
}];
$.ajax({
url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
type: "GET",
dataType: "json",
success: function(data) {
for (var i = 0; i < 1 /*dataWithLabels.length*/ ; i++) {
var statistic = data.current_observation;
dataWithLabels[i]['title'] = statistic.temp_c;
alert(dataWithLabels[i]['title']); // Alert only after data is received
}
}
});

How to send array in AJAX using JSON

I am fairly new to JS and AJAX, and for some reason I can not send my dynamically generated and read data via AJAX. How do I properly send an array via AJAX to PHP script?
I have tried following the instructions but I can not get the AJAX to send the data. The first try was a complete bust, the second gets error:
Uncaught TypeError: Illegal invocation
but it seems to originate from the JS-library instead of my code (though the code is most probably the reason for it!) and I do not know what to do with it.
//first thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
console.log(cu[j].value);
i++;
}
var dynamic_account_value = JSON.stringify(cu);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:dynamic_account_value
}
});
//2nd thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
cu2.push(JSON.parse(cu[j].value));
i++;
}
var tilinrot_lisa = JSON.stringify(cu2);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:tilinrot_lisa
}
});
First, give them something that makes selection easier, like a common class. Second, use jquery serialize
$.ajax({
url : "foo",
data : $(".bar").serialize(),
success : function(response) {}
})
Try this code snippet, Try to send just one variable then go for another & use content type.
u can use //console.log(JSON.stringify(cu)); to view what's inside.
jQuery.ajax({
type: 'post',
dataType: 'json',
data: {your_var:JSON.stringify(cu)},
contentType: "application/json"
});

Categories