How to use $.each with ajax to get JSON? - javascript

I am using ajax to get JSON from an API, however I am having a problem, retrieving the data. The code for ajax function is fine as I am using it elsewhere. I believe that the issue is with the .done(function().
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
//dataType: 'json',
//method: 'GET',
//contentType: 'application/json'
data: {url: developmentURL},
method: 'POST'
})
.done(function(data) {
//var developments = [];
$.each(data, function() {
$.each(this, function(i, obj) {
console.log(i, obj.Name + ' = ' + obj.ItemKey);
//developments.push();
});
});
})
.fail(function() {
alert('Failed to fetch data')
});
This is the code I am using, which just logs loads of 0 "undefined=undefined". However I have the .done(function() working in a jsfiddle, with the JSON hard coded. So I'm not sure where the problem lies.
Here is the fiddle

The data is of string type. Parse the string into JSON before looping:
data = JSON.parse(data);
$.each(data, function() {

If you want to avoid using JSON.parse you can Set the dataType to just 'json' and you will automatically recieve a parsed json response:
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
dataType: 'json', //Uncomment this line
//method: 'GET',
//contentType: 'application/json'
data: {
url: developmentURL
},
method: 'POST'
})
Or you can also make use of jquery $.getJSON api.

I assume the data that you retrive is an array of Json according to your code.
You forgot add key and value in the $.each callback function to loop into each Json value.
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
//dataType: 'json',
//method: 'GET',
//contentType: 'application/json'
data: {url: developmentURL},
method: 'POST'
})
.done(function(data) {
//var developments = [];
$.each(data, function(key,value) {
$.each(value, function(subKey, subValue) {
console.log(subKey, subValue.Name + ' = ' + subValue.ItemKey);
//developments.push();
});
});
})
.fail(function() {
alert('Failed to fetch data')
});

Related

How to properly format data object that includes array of objects for jQuery ajax put request? [duplicate]

I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Base on lonesomeday's answer, I create a jpost that wraps certain parameters.
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
Usage:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
you can post data using ajax as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {
"name":"jonsa",
"e-mail":"qwerty#gmail.com",
"phone":1223456789
};
$.ajax({
type: 'POST',
url: '/form/',
data: Data,
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}

How to clean an XML object to avoid the "Content not allowed in prolog" error?

I have a XML object retrieved from an AJAX call and for which I have done some manipulations:
$.ajax({
url: "url_of_xml",
type: 'GET',
dataType: 'xml',
success: function (xml) {
var sld_doc= $(xml)
// manipulations with the XML file
}
})
The XML file is correctly modified and is how I need it to be (with the added/modified nodes). Now I need to POST the modified XML (to a GeoServer instance):
$.ajax({
url: "geoserver/rest/styles",
type: 'POST',
data: sld_doc,
headers: {
"Content-Type": "application/vnd.ogc.sld+xml"
},
dataType: 'json',
success: function (data) {a
console.log(JSON.stringify(data));
},
error: function (x, e) {
console.log(x.status + " " + x.responseText);
}
});
I'm getting the error: 500 org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
From what I've read, it is caused by characters before the tag at the beginning of the XML doc.
How can I clean the begging of the XML object so that it can be sent correctly to the server ? I'm able to access nodes with sld_doc.find("node_name") but how can I check for invalid characters before the 1st node (<?xml>) ?
At the moment you are passing a jQuery object. Try unwrapping it, and setting the right dataType too:
$.ajax({
url: "geoserver/rest/styles",
type: 'POST',
data: sld_doc[0],
headers: {
"Content-Type": "application/vnd.ogc.sld+xml"
},
dataType: 'xml',
success: function (data) {a
console.log('success');
},
error: function (x, e) {
console.log('error');
}
});

Post JSON data along with id in Jquery AJAX

I'm trying to post JSON data along with 2 ids through a Jquery AJAX post. But I am not able to do it.
Following is my code:
try {
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = { "str": StringJson};
var url = APP_URL+"EditSurvey?";
var param = "SurveyId="+surveyID+"&JSONData="+JSON.stringify(dataValue)+"&UserId="+providerKey;
$.ajax({
type: "POST",
contentType: "application/json",
url: url,
data: param,
async:true,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.error);
},
});
} catch (error) {
alert(error);
}
I get the following error when I debug this in Safari:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and in simulator I get the following error:
Where am I getting wrong? How do I solve this? I have to 3 parameters for post
surveyID
JSON data
userID
Edited:
The webservice is now changed and all 3 params- i.e. 2 ids and one whole json data is passed to the webservice. Still jquery ajax post is not working. See my code below:
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = {"surveyID":surveyID, "userID":providerKey, "str": StringJson};
alert(dataValue);
var url = APP_URL+"EditSurvey";
var param = dataValue;
$.ajax({
type: 'POST',
contentType: "application/json",
url: url,
data: dataValue,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.text);
},
});
edited to include stringJson:
var StringJson = JSON.stringify(MainJSON);
alert(StringJson);
Check if the final json which is being passed is in the exact format as expected by the server.
Try giving:
contentType: 'application/json',
Accept: 'application/json'
See if it helps.
try this one
formData = {
// all your parameters here
param1: param1,
JSONData: formToJSON(),
UserId: providerKey
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: url,
dataType: "json",
data: formData,
success: function(data) {
//success handling
},
error: function(data) {
alert("Err : " + err.error);
}
});
function formToJSON() {
return JSON.stringify({
dataValue: dataValue
});
}

How to update jqx grid using jquery

$.ajax({
url: "RequestHandler?usercommand=showcriticaldatezone&useraction=ShowUserPreferenceDashbord_frm&subCommand=criticaldatezone",
type: 'POST',
dataType: 'json',
data: dateText,
contentType: 'application/json',
async:'false',
cache:'false',
success: function (data) {
var parsedJSON = JSON.parse(data);
var tempdate;
alert("parse json - "+parsedJSON.length);
js= [];
for (var i=0;i<parsedJSON.length;i++) {
alert(" critical date is -:"+parsedJSON[i].CriticalDate);
js.push(parsedJSON[i].CriticalDate);
//tempdate='{"Date":['+'"'+ parsedJSON[i].CriticalDate + '"' + ']}';
}
tempdate='{"Date":'+JSON.stringify(js)+'}';
alert("stringify is -:"+tempdate);
selectedDate=tempdate;
jqxgriddata=data;
$(this).datepicker("refresh");
jQuery("#myGrid").setGridParam({ 'data': data}).trigger("reloadGrid");
alert('sucess!');
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
i am using above code to refresh grid after server response but not success i am using jqx grid Server response is json array i am able to display grid at first time but not able to refresh it please help

Reading values from ajax return in json format

In ajax return, i am getting json as
[{"colourname":"red,yellow"}]
i want to fetch "red,yellow" string from json ,
ajax call se ,
$.ajax({
type: "POST",
url: "loadData.php",
data: {
productid: 'getId'
}
}).done(function (msg) {
alert('get ' + msg);
});
I tried ,
msg[0].colourname
msg["colourname"]
Nothing worked how can i access values?
The response returned by $.ajax in done is a raw string, not a JavaScript object. Set dataType: 'json' in the ajax configuration and jQuery will parse the JSON msg as a JavaScript object.
$.ajax({
type : "POST",
url : "loadData.php",
data : {
productid : 'getId'
},
dataType: 'json',
}).done(function(msg) {
alert('get '+msg);
});
Setting the dataType explicitly is not required if you send the server response with Content-Type: application/json
BTW, you should use an array for colourNames: {"colournames":["red","yellow"] }
try this
$.ajax({
type: "POST",
url: "loadData.php",
dataType: 'json'
data: {
productid: 'getId'
}
}).done(function (msg) {
alert('get ' + msg);
});
});

Categories

Resources