ajax json : how to retrieve data from json object received by ajax? - json

Here is the code:
$.ajax({
url: MyURL,
method: 'GET',
processData: true,
contentType: 'application/json;',
dataType: "json",
success: function(data) {
alert("Success data= "+JSON.stringify(data));
var count = Object.keys(data).length;
alert("count = "+count );
result=data[0];
alert("result.CountryName:"+ result.CountryName);
alert("total " + keys.length + " keys: " + keys);
error: function(data) { alert("ajax Error"); },
});
The 1st alert seems ok and gives:
Success data= "[{\"CountryName\": \"france\", \"Currency\": \"Euro\", \"PriceMax\": 500.00, \"PriceStep\": 50.00, \"PriceMin\": 100.00}]"
From the firebug/network/response i see the same data (with the backslash!!)
The 2nd alert gives 107. Apparently each character is an object ?
But when i check the syntax on http://jsonlint.com/ the json is correct.
Finally the last alert gives: undefined.
So what is wrong ?
Thank you for your help

The data you're sending is an array containing a single object. You'll need to use data[0]['CountryName'].

The response that you have is not an JSON object, it is a String. So you need to parse it to a JSON and then take the first position of the array.
json_data = JSON.parse(data)
result = json_data[0]
and then you use a property of that object:
result.CountryName

The problem was the slash in the json string.
I read Why does JSON returned from the django rest framework have forward slashes in the response? and make some modif in my django code.
i changed return JsonResponse(simplejson.dumps(data), safe=False)
to return JsonResponse(data, safe=False) and the slash disappeared then the javascript code worked.
Thanks for your help Daniel and Rubico

Related

How to JSON parse using form.errors.as_json() in Django return JsonResponse(data)

In Django, I tried using form.errors.as_json() to get all form errors and here is sample json data strings.
{"password2":[{"message": "This password is too short. It must
contain at least 8 characters.","code":"password_too_short"}]}
I wanted to loop and get all under "message" key in json so I can use it to notify the user after ajax call.
Thanks
Anyways, I just resolved my issue and just wanted to share what I did.
views.py
if form.is_valid():
...
else:
# Extract form.errors
errMsg= None
errMsg = [(k, v[0]) for k, v in form.errors.items()]
return JsonResponse(errMsg)
Ajax Event
$.ajax({
method: "POST",
url: '\your_url_here',
data: $form.serialize(),
cache: false,
dataType: "json",
beforeSend: function(){
//Start displaying button's working animation
//Do some button or loading animation here...
}
},
success: function(jResults)
{
//This line is to remove field name display
var strErr = jResults + ''; //make json object as string
strErr = strErr.split(",").pop();
alert(strErr);
}
});
Hope this help to anyone out there facing similar issue. By the way, I'm using Django 2.0 and Python 3.6+
Thanks
MinedBP
The correct answer should be:
return HttpReponse(form.errors.as_json(), status=400).
In the AJAX call you can get the content doing:
`$.post("{% url 'your_url'%}", your_payload).done(function(data) {
do_something();
}).fail(function(xhr){
// Here you can get the form's errors and iterate over them.
xhr.responseText();
});`
You are sending a 200 HTTP response, that it is wrong, you should return a 400 HTTP response (Bad request), like Django do without AJAX forms.

Unexpected end of JSON input... SO Wants more info

I'm confused... What's wrong with this?
Couldn't post without changing the title... I seriously don't know what's wrong
$(document).ready(function(){
$("#fmob").click(function(){
var mobname = $(this).attr("data-value");
console.log(mobname);
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: {mobname: 1},
dataType: "json",
success: function(data){
if(data.response === true){
$("#fresponse").html(data.result);
}else{
$("#fresponse").html(data.result);
}
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});
});
I looked up here Unexpected end of JSON input from an ajax call
but somehow not what I expected... What's wrong? Thanks.
Try this approach:
$(document).ready(function(){
$("#fmob").click(function(){
var mobname = $(this).attr("data-value");
console.log(mobname);
var data = {}; // setup a data object
data[mobname] = 1; // add the property with the key of the value of the "mobname" variable, with the data of 1 (per question)
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: data, // pass the data object as the POST data instead of defining an object inline
dataType: "json",
success: function(data){
if(data.response === true){
$("#fresponse").html(data.result);
}else{
$("#fresponse").html(data.result);
}
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});
});
Note the lines with comments, above.
In this approach, we setup a data object and specify a property using the value of the "mobname" variable, instead of defining the property inline. This allows us to use the dynamic value of the variable as the key for the property.
I guess the problem is with the line: data: {mobname: 1}
As you can't assign a variable name as object property like that... it should be inside a square brackets like this data: {[mobname]: 1}
EDIT: if you aren't using browser supported by ES 2015 you could even do
data: JSON.parse('{"'+mobname+'":1}')
EDIT 1 if you want to send the json data as string and convert that on php side you could simply do data: '{"'+mobname+'":1}'
This might cause your ajax call to fail, and might not return a JSON as you're expecting (using the line dattype:JSON);
So removing datatype:JSON can also help you by showing what you're doing wrong
JSON objects are differentiated from standard JavaScript objects by using double quoted in both the key and the value - unless either is an integer.
It is explained in the relevant W3Schools site.
Therefore, in your AJAX request, you have to send a properly formatted JSON object:
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: {"mobname": 1}, //here's the change
dataType: "json",
/* rest of the code */
You can of course pass a variable as well:
var JSON_obj = {"mobname": 1, "othermob": 2, /*rest of the JSON */ };
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: JSON_obj, //here's the change
dataType: "json",
/* rest of the code */
Again, with properly formatted JSON objects (and with properly included JS script if it's in another file), this should work.

How to use a list of objects or array in json post request to a WebService?

as described in the title, I'm trying to call a WebService method via JSON/Ajax in JavaScript with several String parameters and 2 lists or arrays.
For now everything worked fine with single parameters in this format:
var WSParameters = "{pParam1: 'abc', pParam2: 'def'}"
$.ajax({
type: "POST",
url: "WebService.asmx/" + webMethod,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: WSParameters,
success: function (result) {
// stuff to be done on if request was successful
},
error: function (message) { alert('Error loading data! ' + message.responseText); }
});
But now I need to provide the web service method a list/array of values. The web service method looks like this:
[WebMethod(true)]
public void editExistingSystem(System.Collections.Generic.List<String> pFirstList,
System.Collections.Generic.List<String> pSecondList,
String pParam1,
String pParam2)
{
// Stuff
}
I guess it should be something like this, but obviously this didn't work:
var WSParameters = "{pFirstList: 15,4,13, pSecondList: 'gr00001_96594737', pParam1: 'abc', pParam2: 'def'}"
Could you please help me with finding the correct syntax to define a list in this parameter list?
Thanks a lot in davance
Br
vm370
As so often, I found the solution almost right after asking the question...
Sorry guys for bothering you. The correct paramter string to the example in my starting post would be:
var WSParameters = "{pfirstList: ['15','4','13'], pSecondList: ['gr00001_96594737'], pParam1: 'abc', pParam2: 'def'}"
Thanks and best regards
vm370

JSON, invalid label, issue consuming JSON

I have an issue with my JSON. We area getting it from a SOAP service I believe. I am using jQuery AJAX to try to consume the JSON. We are using the Asp.NET solution so I know about the "d" security feature and have in my dataFilter a way to try to get around that. I am getting the JSON back in Firebug but not to my local machine. The Service is on a domain separate from my local machine. I know about the cross domain policy issue but seems to be consuming the JSON in Firebug when I put the dataType as "jsonp" in the jQuery AJAX call.
If I set my dataType as "json" I get nothing back in Firebug.
The thing is my JSON has "\" slashes in it. I guess that is why Firebug is giving me an "invalid label" error. But I am not sure of that.
How can I filter out the "\" without doing the server side code again.
How can I just get the JSON back and alert on my page.
My jQuery Ajax call is below.
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "http://www.myexternaldomain.com/jservice/myservice.svc/CurrentJsonDataFullWeatherPanel",
data: "{}",
dataType: "jsonp",
dataFilter: function(data) {
// This boils the response string down
// into a proper JavaScript Object().
var msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
success: function(msg) {
// This will now output the same thing
// across any current version of .NET.
alert(msg);
},
error: function (result) {
alert('Failed: ' + result.status + ' ' + result.statusText);
}
});
});
My JSON output in Firebug shows like this.
{"d":"[{\"AirTemperature\":\"57.3\",\"BarometricPressure\":\"30.08\",\"CurrentRainRate\":\"\",\"DewPointTemperature\":\"30.7\",\"HeatIndex\":\"57.3\",\"HourlyRainAmount\":\"0.00\",\"LocalObservationTime\":\"10/14/2011 11:16:07 AM\",\"MonthlyRainAmount\":\"\",\"RelativeHumidity\":\"36\",\"SnowDepth\":\"0.0\",\"SolarRadiation\":\"\",\"SunRise\":\"7:09 AM\",\"SunSet\":\"6:22 PM\",\"TodayRainAmount\":\"0.00\",\"Visibility\":\"6561\",\"WindChill\":\"57.3\",\"WindDirection\":\"2\",\"WindGust\":\"11.4\",\"WindGustDirection\":\"92\",\"WindSpeed\":\"4.9\",\"YearlyRainAmount\":\"22.24\",\"StationTime\":\"10/14/2011 11:15:24 AM\"}]"}
Any suggestions?
Do I need to use a different way than jQuery to consume my JSON?
I should add that my fail alert is sending back 200 success but hitting the error.
Help is much appreciated. Thanks in advance.
Replace eval('(' + data + ')'); with $.parseJSON(data)
Docs: http://api.jquery.com/jQuery.parseJSON/

Using jQuery and JSON with AJAX responseText?

Ok, I'm a bit new when it comes to jQuery and json. If I'm using json as my return type, can I still retrieve responseText from an XMLHttpRequest object?
here's the code that i'm using:
json response: {"clients": []}
$.ajax({
type: "POST",
url: "/myurl/whatever.php",
data: myData,
dataType: "json",
success: function(msg){
status.html(msg[0]);
},
error: function(msg) {
status.html("Error: " + msg[0]);
}
});
is the use of msg[0] correct if i want to output the json response or am i missing something?
how can i still use the above code with XMLHttpRequest to get the status, responseText, etc.
thanks, all!
As far as I know, the call to $.ajax returns a XHR object, and from that the responseText can be extracted, e.g.:
var xhr = $.ajax( {
url:' someInfo.php',
data: 'which=squirrels',
asynch: true
} );
var resp = xhr.responseText;
The response text will contain a json string, which would need to be converted to an object to be of any use.
If you want to use the response as a json object directly within your success: function, do as #cloudhead suggested, and use msg. The dataType : "json" in your options takes care of the conversion for you.
If you're using json, then you get a json object back, not an XML object. You can output it directly, without using [0].