Why does JQuery try to parse ajax responses as xml in Firefox? - javascript

var url = "/MyApp/pspace/filter";
var data = JSON.stringify(myData);
$.post(
url,
data,
function(response, textStatus, jqXHR) {
console.log("response: " + response);
},
"json"
);
In reality, response should be a json string.
In Chrome, response is a string that I can parse with $.parseJSON().
In Firefox, response is an XMLDocument (with a parse error), unless I use dataType: "text". Why?

If you are setting "json" as your response type jQuery should parse it into an object for you automatically. If you forgot to tell jQuery what type of response to expect different browsers will treat it differently.
The solution is to make sure you specify your response type as "json" and then of course to make sure the data that is being returned is an actual JSON string.

Related

What's diffrence in jQuery ajax dataType="json" vs JSON.parse()

Is there any real diffrence between using dataType='json' and parse response by JSON.parse(response) in jQuery Ajax?
$.ajax({
url: path,
type: 'POST',
dataType: 'json',
data: {
block : lang,
},
}).done(function(response, textStatus, jqXHR)
{
output = response;
});
VS
$.ajax({
url: path,
type: 'POST',
data: {
block : lang,
},
}).done(function(response, textStatus, jqXHR)
{
output = JSON.parse(response);
});
dataType: 'json':
Sets the Accept request header to tell the server that JSON is the desired response format
Attempts to parse the response as JSON regardless of what the server's Content-Type response header says the format is. (jQuery's default behaviour is to use the Content-Type to determine the correct parser).
JSON.parse:
Attempts to parse the response data as a string of JSON regardless of what it actually is (if the server responds with correctly labelled JSON, this will error since it will have already been parsed by jQuery).

OData returns array instead of JSON - How to convert?

I've been trying to figure how to properly receive an OData response in Javascript for a couple of days. The problem is the response is formatted as an array instead of JSON, so the function JSON.parse(mydata) does not work with the data I am receiving.
My question is two-fold: What is the proper way to request OData to send a response as JSON and/or how do I format my current response to be JSON?
Here is the code that I am using:
$.ajax({
type: "GET",
url: requestUri,
dataType: "script",
accept: "application/json",
success: function(data, request) {
var jsonData = JSON.parse(data);
},
error: function(msg) {
alert(msg);
}})
Here is an example response of logging the variable data with console.log:
{"#odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]}
The problem is the response is formatted as an array instead of JSON
It can't be. You can't send "an array" over HTTP. You have to encode it somehow … e.g. as JSON.
jQuery will, unless you override it with the dataType option, use the Content-Type HTTP response header to determine how the data is encoded. If it is JSON, it will parse the JSON.
The value of data is what you would get if you read the raw responseText and passed it through JSON.parse.
So just don't try to parse it manually. jQuery has done it for you.
Skip the step:
var jsonData = JSON.parse(data);
… and just work with data.
NB: The output of JSON.parse is an object, array or other JavaScript data type. JSON data is what you get from JSON.stringify.
If the response is in OData format, as your example shows, but you want it in JSON format that can be parsed by JSON.parse, add $format=json to the OData query, so long as the OData endpoint supports it. I know Dynamics 365 does not.
You can add it to a variable and access it just like that.
var v={"#odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]};
//v.value[0] is a json object
console.log(v.value[0]);
or skip the assignment altogether and access this way:
data.value[0]
data.value[0].Genre
data.value[0].RunTime
etc....

Ajax calls to a CORS disabled service

Is it possible to use javascript to consume data from a webservice that is CORS disabled, only returns XML data (no option for json/jsonp) and over HTTPS? I do not have control of this webservice to make changes.
At best, if I run the following ajax I'll see an xml response getting sent back (using Chrome's developer tools) however my success function isn't being hit and I'll end up with an exception 'Unexpected syntax <' because it's anticipating a json padded response.
If I change dataType to just 'xml' I will get an error "Access-Control-Allow-Origin" not found in header response. Which is what I'd except since they have not enabled CORS.
$.ajax({
url: 'https://' + myURL + querystring,
username: usr,
password: pwd,
dataType:'jsonp text xml',
type: 'GET',
success: function (data) {
console.log( "success" );
},
cache: false,
contentType: false,
processData: false
});
Not directly.
You can write your own webservice that interacts with it and then access your service from JavaScript instead.
You have mentioned that , when used dataType jsonp,i would get the response.I guess that the webservice support jsonp,otherwise,the $.ajax couldn't get the response text.And then, you mentioned:
'Unexpected syntax <' because it's anticipating a json padded response
The dateType of jsonp in jquery will force the response text to be transformed from plain text to json object,but unfortunately the response text is returned in format of XML.
Since the webservice support jsonp and the jquery require jsonp must be return in json format, why not use the native javascript to resolve it?
function parseXml(xml) {
console.log('the return xml ',xml);
}
document.write('<script type="text/javascript" src="https://xxxx?param=xx&callback=parseXml"><\/script>');
At last,please don't reduce my marks now,its number has nearly been down to zero for this qustion.

JSON response from Python json.dumps

I am trying to send a Django HttpResponse encoded as JSON to Javascript.
Python:
response_data = {}
response_data['status'] = 'incomplete'
return HttpResponse(json.dumps(response_data), content_type="application/json")
Jquery:
function auth_request(){
$.ajax({
url: AUTH_ENDPOINT + "myid0001",
context: document.body,
success: function(response){
console.log(response);
console.log(response.status);
if(response.status == "incomplete"){
//do something here
}
}
}
});
}
The console prints {"status": "incomplete"} for the first console log and undefined for the console.log function accessing the status element.
I tried using JSON.parse(response) but I get the error
Uncaught SyntaxError: Unexpected token a in the jquery.js file which I believe is indicating that the object is already a JSON object. However, if I check the type of the object, it displays string. How can I access the elements of the response JSON object?
You need to parse the Json back into a JS object when it's received. Otherwise, it's just text.
jQuery will do that for you if you specify dataType: "json" in the Ajax call.
I found the solution. It turns out that my Django setup was returning some additional string items so when I tried to set dataType: "json" (as #Daniel Roseman suggested) or in the jQuery function or use JSON.parse(response) I received an error. I was able to remove the extra string and it worked properly.

Access json data from php

I have a problem accessing JSON data. I'm new to JSON and jquery so there is probably a easy solution to it and I would be glad to find out.
My jQuery:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
}
);
currentPage.php:
$returnArray['left'] = 'test_left';
$returnArray['right'] = 'test_right';
$returnArray['numLeft'][] = 1;
$returnArray['numRight'][] = 2;
$returnArray['numRight'][] = 3;
print json_encode($returnArray);
I tried to access the data like this:
data.left
data['left']
but it returns blank, how is the best way to access the data in the HTML-file?
I could be wrong, but I don't think the post method assumes a data return-type of json. You could set that by changing the ajax function to:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
},
"json"
);
Provide the datatype you expect to get as parameter to the .post() method (in your case json):
$.post("currentPage.php",{'currentPage': 1},
function(data){
$("body").append(data);
},
'json' // <-- add the expected datatype
);
I think the default is to treat the result as HTML. Read the documentation.
jQuery.post( url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ] )
urlA string containing the URL to which the request is sent.
dataA map or string that is sent to the server with the request.
success(data, textStatus, XMLHttpRequest) A callback function that is executed if the request succeeds.
dataType The type of data expected from the server.
In JQuery, you need to set the return data type (dataType) to json so the function knows what type of data to expect and process. From the manual:
"json": Evaluates the response as JSON
and returns a JavaScript object. In
jQuery 1.4 the JSON data is parsed in
a strict manner; any malformed JSON is
rejected and a parse error is thrown.
(See json.org for more information on
proper JSON formatting.)
You can do this with the full $.ajax() call, or you can use $.getJSON(). There is no HTTP POST shortcut to return JSON (i.e. $.postJSON doesn't exist), but you can supply the dataType parameter to $.ajax() or just add the parameter to $.post() . When you have a JSON object, use json.keyName to access the data.
$.ajax({
url: "currentPage.php",
data: {
'currentPage': 1
},
dataType: "json",
type: "post",
success: function(data) {
$("body").append(data);
}
});

Categories

Resources