Javascript: How to tell whether AJAX response is JSON - javascript

I've got an AJAX request that expects JSON in response.
But there's a possibility that what gets returns may not be JSON, but rather an HTML error page (unfortunately, with response type 200).
How can I tell whether the response is JSON or not?
(I'm using jQuery, if that helps. But I can't use any plugins.)

Well, if you are using jQuery and you specify the dataType property of the $.ajax() call to json then jQuery will try to parse the JSON, and if it isn't JSON should call the error() callback.
$.ajax({
url: '/my/script.ext',
dataType: 'json',
success: function(data, textStatus, jqXHR) { /*YAYE!!*/ },
error: function(jqXHR, textStatus, errorThrown) { /*AWWW... JSON parse error*/ }
});
EDIT
For anyone not using jQuery that lands here, the basic idea is to try and parse it as json and catch the error:
var data = 'some_data';
try {
data = JSON.parse(data);
} catch(e) {
//JSON parse error, this is not json (or JSON isn't in your browser)
}
//act here on the the parsed object in `data` (so it was json).

jQuery auto-detects the dataType:
If the response is JSON, a properly behaving application would set the Content-Type to application/json.
So all you have to do, if the server is well-behaving, is to test if the Content-Type header in the response starts with application/json.
By chance, jQuery already does this by itself:
$.get('/foo', function(data, status, xhr, dataType) {
if ('json' === dataType) {
// Yay that's JSON !
// Yay jQuery has already parsed `data`
}
});
jQuery detects the dataType and passes it as 4th parameter of the callback function. If the dataType is JSON, it parsed the JSON string and parses the resulting value as first parameter of the callback.

Seems like a good use of try catch:
try {
$.parseJSON(input)
} catch(e) {
// not valid JSON
}

jQuery parseJSON function can be used for this. It will throw an exception then you can catch it go ahead.
data = '{}';
try {
json = $.parseJSON(data);
} catch (e) {
// not json
}

try {
jQuery.parseJson(json_string_here);
} catch(e) {
... malformed json ...
}

Related

Why does my ajax success callback-function not work as expected?

I code this ajax request but I don't know why the code in the success method doesn't work
Even though in the networks in chrome browser appear state: 200ok
this is ajax code:
$("#noti_filter").click(function(){
//first add item into cart
var item_id = 'test';
$.ajax({
method:"POST",
//contentType:"application/json",
url:"../html/notifies.php",
data:{product_id:item_id},
dataType: "json",
success:function(data,state) {
console.log(data);
console.log(state);
alert('ajax success');
}
});
});
the problem is that alert or console Not to mention the others code
success:function(data,state)
{
console.log(data);
console.log(state);
alert('ajax success');
}
From the ajax events docs:
success (Local Event)
This event is only called if the request was successful (no errors from the server, no errors with the data).
Since your server responded with 200 OK that means we can route out problems with the server and are left with errors with the data.
From the ajax docs (only the relevant parts):
dataType
The type of data that you're expecting back from the server.
The available types (and the result passed as the first argument to your success callback) are:
"json": Evaluates the response as JSON and returns a JavaScript object.
...
The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
So most likely the data returned by the server is being rejected by ajax in which case a parse error should be thrown.
This would be an example of how to implement an error handler:
$("#noti_filter").click(function(){
//first add item into cart
var item_id = 'test';
$.ajax({
method:"POST",
//contentType:"application/json",
url:"../html/notifies.php",
data:{product_id:item_id},
dataType: "json",
success: function(data,state) {
console.log(data);
console.log(state);
alert('ajax success');
},
error: function(err) {
console.log(err.responseText); // <-- printing error message to console
}
});
});
You defined the dataType as json. The dataType is the type of data that you're expecting back from the server. Does your server responds json?
I assume the result of your 200-ok-server-request is probably not in json format, so the parsing fails and your success-callback is not called. You can catch the error with error callback function.
After that you know the exact reason.

Fetch data from a complex JSON

I'm new to javascript and JSON and I've been given a task to complete. Please find the JSON in the following link,
http://pastebin.com/0BY3eptF
According to me the above is a very complex JSON.
I'm trying to fetch the out from a WSDL via ajax
success: function(api) {
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
This doesn't work. I would like to learn how to iterate each JSON string loop. I also see an array which is WSResult[]. A neat javascript with explanation will help me a lot. Thank you.
Some web services return content type as plain text instead of json, you have to manually convert into json. below code will help you do the same.
success: function(api) {
if (api.constructor === String) {
api = JSON.parse(api);
}
console.log(api.SearchResult);
}
To loop through api.SearchResult.Result.WSResult array, please find below code
$(api.SearchResult.Result.WSResult).each(function (index, val) {
// here val is single object of WSResult array
});
success: function(api) {}, here, api is still a string, you have to parse it to JSON first:
success: function(api) {
var api = JSON.parse(api);
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
Not a complete answer, but some useful pointers:
$ajax({
url: 'http://myURL',
// specify the datatype; I think it overrides inferring it from the document MIME type
dataType: 'json',
success: function (api) {
// provided your data does come back as a JSON document
// you should be able to access api.SearchResult
},
error: function( jsXHR, textStatus, errorThrown) {
// always have an error handler, so you can see how it went wrong.
}
);
Read the section on dataType here, as it may solve your problem

Cross-domain AJAX call returning string JSON, instead of JSON object

I am making a cross-domain AJAX call, and I am not sure if I am doing something wrong or the providers of the API call is incorrectly returning the JSON. Whenever I get the response from the API call, it is a string instead of a JSON object. Here is my AJAX call.
$.ajax({
async: false,
dataType: 'jsonp',
url: 'http://cross-domain/getSummaryStat.action',
data: { minDailyDate: start_param, maxDailyDate: end_param },
success: function(response) {
map = {
gamefuse: response["ROM-GF-Live"],
facebook: response["ROM-FB-Live"],
kongregate: response["ROM-Kongregate-Live"],
yahoo: response["ROM-Yahoo-Live"]
}
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
When the response comes back, here is response.result
"[{"dayRetention1":"0.01453800063053","visit":"601","installs":"203"},{"dayRetention1":"0.122484891199019","visit":"33863","installs":"10949"]"
NOTE: I set dataType to jsonp because it is a cross-domain AJAX call, and I was getting an error without it.
First, It looks like the returned string isn't even in correct JSON form. It's missing a close bracket at the end.
If this doesn't fix it then the issue here is probably on the server side. Since JSONP is JSON with padding, your return function shouldn't be:
function_name("the string that I return");
Instead you should have:
function_name({
"name":"Bob Loblaw",
"age":40
});

Accessing values of a JSON-encoded object

I am sending a JSON encoded array from my controller to my view page. I am doing this on my view page to get the data:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data[0].message);
});
}
The data is like this
{"message":"hello!"}
I am alerting the value of message but my alert giving me undefined. My question is how can I access values of JSON array?
I am new to JSON so I don't know much about JSON.
Try changing your function to:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data.message);
}, 'json');
}
This is because jQuery probably doesn't know that the response data is JSON, so it's assuming that it's plaintext. You can explicitly specify it in $.get as the last parameter as in the revised code, or configure your server to send the response with the HTTP Content-Type header of application/json.
I'm assuming this because message is not a property of a String and that's why you're getting undefined.
Alternatively, you may use $.getJSON:
function () {
$.getJSON('http://localhost/Location/loc', function(data){
alert(data.message);
});
}
Also note that I have changed the alert to data.message. See Knaģis' answer for explanation.
You data contains a single object, not an array.
In your case use alert(data.message); instead.
An array is defined using [] brackets, for example [{message:"hello"}, {message:"world"}] is an array with two objects in it.
OK, if this does not work:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data.message);
});
}
try this:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data.message);
}, 'json');
}

JSON.parse not parsing Json string. Serializing with JavaScriptSerializer

I have a serialized string comming from the controller to a view:
Controller:
var serialize = new JavaScriptSerializer();
return Json(new
{
data = serialize.Serialize(obj)
}, JsonRequestBehavior.AllowGet);
Json string:
[{"indiceName":"Caracter","indiciId":24,"indiceId":1,"tamanhoIndice":10,"mask":null,"indiceObr":1},
{"indiceName":"Numérico","indiciId":25,"indiceId":2,"tamanhoIndice":10,"mask":null,"indiceObr":0},
{"indiceName":"AlfaNumérico","indiciId":26,"indiceId":3,"tamanhoIndice":10,"mask":null,"indiceObr":0}]
As far as I know, modern browser should be able to parse that string with a simple
Json.parse()
View:
success: function (data)
{
$('.dinamic').remove();
console.log(data);
var obj2 = JSON.parse(data);
console.log(obj2);
}
I am able to see that string in the first console.log, but I get nothing from the second.
Is there any thing else I should be looking at because all the post I have read people only do it as simple as it is with a single JSON.parse.
I am using latest version of google chrome ,firefox and IE so it should work.
Although your success function is not shown in context of the other AJAX options being given, I would guess you are passing a dataType option of "json", or are using $.getJSON or something similar.
If that is the case, jQuery has already parsed the JSON for you by the time it passes it into success so you do not need to (and cannot) parse it again. You can simply use your data structure (data[0]. indiceName and etc).
(The below code is running live at http://jaaulde.com/test_bed/GuilhermeLongo/ )
Consider the following PHP (stored in json.php):
<?php
exit('[{"indiceName":"Caracter","indiciId":24,"indiceId":1,"tamanhoIndice":10,"mask":null,"indiceObr":1},{"indiceName":"Numérico","indiciId":25,"indiceId":2,"tamanhoIndice":10,"mask":null,"indiceObr":0},{"indiceName":"AlfaNumérico","indiciId":26,"indiceId":3,"tamanhoIndice":10,"mask":null,"indiceObr":0}]');
And the following JS:
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$.ajax({
url: 'json.php',
type: 'get',
dataType: 'json',
success: function (data) {
console.log(data[0]);
console.log(data[0].indiceName);
},
error: function () {
throw new Error('AJAX request error occurred.');
}
});
</script>
It results in the following outputted log info:
GET http://jaaulde.com/test_bed/GuilhermeLongo/json.php
200 OK
99ms
jquery.min.js (line 3)
Object
{indiceName="Caracter", indiciId=24, indiceId=1, more...}/test_...eLongo/
(line 8)
Caracter

Categories