how to know if the result of an ajax request is json? - javascript

I'm doing an ajax request using $.get and as result I could get a simple string or JSON, how to know if the result is JSON (object) or not ?
EDIT:
can I return a string and somehow transform it into object/JSON ?

Its not 100% but server probably set responce header: Content-Type: application/json. So you can try to check it:
$.ajax({
url: 'url',
success: function(data, textStatus, xhr){
var spoiler = xhr.getResponseHeader('Content-Type');
spoiler == 'application/json' ? alert('JSON received') : alert('Not JSON received');
}
});
Sure, it worked only if your server sets its headers in correct way.
One more way - is try to create a function and catch errors you may have.
try {
x = ( new Function('return ' + received_data) )();
}
catch (e) {
console.log('Its not a JSON data... or its invalid.');
}

Use the typeof method to determine if it's an object or a String. If you want to convert a String to a JSON object, and if you trust the source you can use eval. Otherwise use a JSON parser, such as http://www.json.org/json_parse.js

Usually you would expect to know what the data type is, but if for some reason you don't, how about checking the 'Content-Type' header. In theory it should be 'application/json':
function responseHandler() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
if(http_request.getResponseHeader("Content-Type") == 'application/json') {
// JSON
}
else {
// Not JSON
}
}
}
}
Of course, you'll have to check that the server is setting the Content-Type header correctly. Also, not sure if this will work in IE- probably not.

You can use getJSON() instead
http://api.jquery.com/jQuery.getJSON/
For the edit:
You can use
$.ajax({
type: 'get',
cache: false,
url: service,
error: function(XMLHttpRequest, textStatus, errorThrown){
failureFunction(XMLHttpRequest, textStatus, errorThrown);
},
success: function(data){
successFunction(data);
},
dataType: 'text'
});
With dataType Text, and parse for JSON from there.
jQuery.parseJSON( json ) - http://api.jquery.com/jQuery.parseJSON/

You should know. Each url should only return one type of data.

You know how the data is coming and you can do a null check to
Like
if it is a string constructed json , do a Eval of result
IF(EmployeeDetails.SalaryDetails.lenght)
{
forloop()
}

Related

Sending JSON data with jQuery not working

Simple request being made
var username = {'username' : 'tom'};
var request = $.ajax({
url : 'test.php',
method : 'GET',
data : JSON.stringify(username),
dataType : 'json'
});
request.done(function(response) {
response = JSON.parse(response);
console.log(response);
});
request.fail(function(xhr, status, error) {
console.log(error);
});
PHP:
<?php
echo json_encode(array("bar" => "bar"));
?>
Still getting error, no idea why
that's because the server is returning a non valid JSON string. Try to check what the server is returning. This may happen if your server is throwing an error. In your case, I think the error you are trying to parse is not a JSON string. You might want to check that out as well.
You can use this link to validate your JSON.

Node.js and Express - Sending JSON object from SoundCloud API to the front-end makes it a string

I have been using an http.get() to make calls to the SounbdCloud API method to receive a JSON object that I would like to pass to the browser. I can confirm that the data I receive is an object, since I the typeof() method I call on the data prints out that it is an object.
var getTracks = http.get("http://api.soundcloud.com/tracks.json?q="+query+"&client_id=CLIENT_ID", function(tracks) {
tracks.on('data', function (chunk) {
console.log(typeof(chunk)); // where I determine that I receive an object
res.send(chunk);
});
//console.log(tracks.data);
}).on("error", function(e){
console.log("Got error: "+e);
});
But when I check the data I receive in the AJAX request I make in the browser, I find that the data received has a type of String (again, I know this by calling typeof())
$('#search').click(function(e){
e.preventDefault();
var q = $("#query").val();
$.ajax({
url: '/search',
type: 'POST',
data: {
"query": q
},
success: function(data){
alert(typeof(data));
alert(data);
},
error: function(xhr, textStatus, err){
alert(err);
}
})
});
I would appreciate the help, since I do not know where the problem is, or whether I am looking for the answer in the wrong places (perhaps it has something to do with my usage of SoundCloud's HTTP API)
JSON is a string. I assume you need an Object representing your JSON string.
Simply use the following method.
var obj = JSON.parse(data);
Another example would be:
var jsonStr = '{"name":"joe","age":"22","isRobot":"false"}';
var jsonObj = JSON.parse(jsonStr);
jsonObj.name //joe
jsonObj.age // 22

Seems that no response received on getJSON

I am sending the jsonp request as:
var jsoncallback = "?jsoncallback=?"
$.getJSON( reportURL + jsoncallback, {
tags: "",
tagmode: "any",
format: "json"
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
alert( item );
});
});
I have put an alert to see if the request works. On server side, in node js file I am responding to request as:
..
console.log("request received");
response.writeHead( 200, { "Content-Type": "application/json" } );
..
response.end();
In the logs I can see that the request received. The problem is that no alert windows pops up.
What could be the reason to this?
I just reponse.writeHead(...) and (for testing reasons - just the head and end) response.end()
With the jsoncallback=? in the URL, jQuery is expecting a JSONP <script> as a response. For this to work, the server should at the very least write out the "padding."
That is a call to the function named by jsoncallback. And it won't be just ? -- jQuery replaces that with a pseudo-random function name along the lines of jQuery1910123456789_0123456789. For that, the response should at least be:
jQuery1910123456789_0123456789();
You'll need to get the value from the request.url:
var parsedUrl = url.parse(request.url, true);
var query = parsedUrl.query || {};
if ('jsoncallback' in query) {
response.write(query.jsoncallback + '();');
}
// ...
And, once you have data to output with it:
if ('jsoncallback' in query) {
response.write(query.jsoncallback + '(' + JSON.stringify(data) + ');');
} else {
response.write(JSON.stringify(data));
}
Have you confirmed the JSON is correctly formatted? Check it against http://jsonlint.com/.
From the getJSON() docs:
As of jQuery 1.4, if the JSON file contains a syntax error, the
request will usually fail silently.

Jquery JSON response handling

I have an ajax query written in jQuery that is returning valid JSON in this format
$.ajax({
type : 'POST',
url : 'ajax/job/getActiveJobs.php',
success : function(data){
if(data[''] === true){
alert('json decoded');
}
$('#waiting').hide(500);
$('#tableData').html(data['content']);
$('#message').removeClass().addClass((data.error === true)
?'error':'success').text(data.msg);
if(data.error === true)
$('#message')
},
error : function(XMLHttpRequest, textStatus, errorThrown){
$('#waiting').hide(500);
$('#message').removeClass().addClass('error').html(data.msg);
} })
I take it this is not correct as it is not displaying the data, if I use
$('#mydiv').html(data);
I get all of the data back and displayed.
any help is really appreciated
Set the dataType to be json so jQuery will convert the JSON to a JavaScript Object.
Alternatively, use getJSON() or send the application/json mime type.
Either set dataType to json or use var json = JSON.parse(data) to do it manually.
EDIT:
I'm adding this because somebody else suggested eval, don't do this because it gets passed straight into a JSON object without any sanitation first, allowing scripts to get passed leading straight into an XSS vulnerability.
The data is the Json so you will want to do this:
success: function (data) {
var newobject = eval(data);
alert(newobject.msg);
}
or do this:
$ajax({
url: url,
data: {},
dataType: "json",
success: function (newObject) {
alert(newobject.msg);
}
});

Array of Objects via JSON and jQuery to Selectbox

I have problems transferring a dataset (array of objects) from a servlet to a jsp/jquery.
This is the dataset sent by the servlet (Json):
[
{aktion:"ac1", id:"26"},
{aktion:"ac2", id:"1"},
{aktion:"ac3", id:"16"},
{aktion:"ac4", id:"2"}
]
The jsp:
function getSelectContent($selectID) {
alert('test');
$.ajax({
url:'ShowOverviewDOC',
type:'GET',
data: 'q=getAktionenAsDropdown',
dataType: 'json',
error: function() {
alert('Error loading json data!');
},
success: function(json){
var output = '';
for (p in json) {
$('#'+$selectID).append($('<option>').text(json[p].aktion).attr('value', json[p].aktion));
}
}});
};
If I try to run this the Error ('Error loading json data') is alerted.
Has someone an idea where the mistake may be?
Thanks!
If the error function is running, then your server is returning an error response (HTTP response code >= 400).
To see exactly what is going on, check the textStatus and errorThrown information that is provided by the error callback. That might help narrow it down.
http://api.jquery.com/jQuery.ajax/
The way you are setting the data parameter looks a bit suspect (notice JSON encoding in my example below). Here is how it would look calling a .Net asmx
$.ajax({
url: "/_layouts/DashboardService.asmx/MinimizeWidgetState",
data: "{'widgetType':'" + widgetType + "', 'isMinimized':'" + collapsed + "'}"
});
Also the return data is by default placed in the .d property of the return variable. You can change this default behavior by adding some ajax setup script.
//Global AJAX Setup, sets default properties for ajax calls. Allows browsers to make use of native JSON parsing (if present)
//and resolves issues with certain ASP.NET AJAX services pulling data from the ".d" attribute.
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
success: function(msg) {
if (this.console && typeof console.log != "undefined")
console.log(msg);
},
dataFilter: function(data) {
var msg;
//If there's native JSON parsing then use it.
if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
//If the data is stuck in the "."d" property then go find it.
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
handleAjaxError(XMLHttpRequest, textStatus, errorThrown);
}
});

Categories

Resources