Using jQuery and JSON with AJAX responseText? - json

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].

Related

How do I format a url to return only a specific element from the JSON object?

I'm trying to get only the BTC_BTS data from this endpoint:
https://poloniex.com/public?command=returnTicker
How can I format the url to only return that data and not the rest of the ticker pairs?
You can set up a get request to that endpoint and go through the response depending on your language. For JavaScript and jQuery:
$.ajax({
url: "https://poloniex.com/public?command=returnTicker",
method: "GET"
}).then(function(response) {
console.log(response.BTC_BTS);
});

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.

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

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

Parse JSON returned from NODE.js

I’m using jQuery to make an AJAX call to Node.js to get some JSON. The JSON is actually “built” in a Python child_process called by Node. I see that the JSON is being passed back to the browser, but I can’t seem to parse it—-although I can parse JSONP from YQL queries.
The web page making the call is on the same server as Node, so I don’t believe I need JSONP in this case.
Here is the code:
index.html (snippet)
function getData() {
$.ajax({
url: 'http://127.0.0.1:3000',
dataType: 'json',
success: function(data) {
$("#results").html(data);
alert(data.engineURL); // alerts: undefined
}
});
}
server.js
function run(callBack) {
var spawn = require('child_process').spawn,
child = spawn('python',['test.py']);
var resp = '';
child.stdout.on('data', function(data) {
resp = data.toString();
});
child.on('close', function() {
callBack(resp);
});
}
http.createServer(function(request, response) {
run(function(data) {
response.writeHead(200, {
'Content-Type':
'application/json',
'Access-Control-Allow-Origin' : '*' });
response.write(JSON.stringify(data));
response.end();
});
}).listen(PORT, HOST);
test.py
import json
print json.dumps({'engineName' : 'Google', 'engineURL' : 'http://www.google.com'})
After the AJAX call comes back, I execute the following:
$("#results").html(data);
and it prints the following on the web page:
{“engineURL": "http://www.google.com", "engineName": "Google"}
However, when I try and parse the JSON as follows:
alert(data.engineURL);
I get undefined. I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Could anyone advise if I’m doing something wrong building the JSON in Python, passing the JSON back from Node, or simply not parsing the JSON correctly on the web page?
Thanks.
I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Yes, the ajax response is a string. To get an object, you have to parse that JSON string into an object. There are two ways to do that:
data = $.parseJSON(data);
Or, the recommended approach, specify dataType: 'json' in your $.ajax call. This way jQuery will implicitly call $.parseJSON on the response before passing it to the callback. Also, if you're using $.get, you can replace it with $.getJSON.
Also:
child.stdout.on('data', function(data) {
resp = data.toString();
// ^ should be +=
});
The data event's callback receives chunks of data, you should concatenate it with what you've already received. You probably haven't had problems with that yet because your JSON is small and comes in a single chunk most of the time, but do not rely on it, do the proper concatenation to be sure that your data contains all the chunks and not just the last one.

Posting JSON with JQuery

Trying to get JQuery to post JSON to a server:
$.ajax({
url: "/path/to/url",
type: "POST",
dataType: "json",
contentType: "json",
data: {"foo": "bar"},
success: function(){
alert("success :-)");
},
error: function(){
alert("fail :-(");
}
});
Problem is the data appears on the server as "foo=bar" rather than the desired "{\"foo\":\"bar\"}.
I thought specifying either the dataType or contentType params would do the trick, but no.
Anyone know the correct ajax configuration ? [or alternatively a way of serialising the 'data' parameter as JSON prior to posting ?]
Thanks!
You could use json2.js:
data: JSON.stringify({"foo": "bar"})
Datatype is for returned data. Contenttype is not applicable, see here
It can only send strings, I use JSON.stringify on my created javascript objects, in your case you could just manually code the string.
You will also need to access the string on server side, for that if you are using java I can recommened google's gson