Jquery JSON response handling - javascript

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);
}
});

Related

Print JSON string from URL

I'm using ajax to parse JSON data from a URL. I need to capture the parsed array into a variable. How would I go about this? Thanks
function rvOffices() {
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
data: JSON.stringify(data),
dataType: 'text',
success: function( data) {
// get string
}
});
}
rvOffices();
var rvOfficesString = // resultant string
You can use JSON.parse(data) to convert the desired output to JSON, and then access the objects and array indexes from within that with .object and [array_index] respectively:
function rvOffices() {
$.ajax({
url: 'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type: 'GET',
dataType: 'text',
success: function(data) {
var json_result = JSON.parse(data);
//console.log(json_result); // The whole JSON
console.log(json_result.offices[0].name);
}
});
}
rvOffices();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You also don't need to pass any data, as you're performing a GET request.
Hope this helps! :)
So I guess you are not sure about the ajax call, so lets break it..
Ajax call is a simply method to make a request to remote resource (Get/post/put...) the type of request (GET/POST) depends upon your need.
so if you have an endpoint that return simply data as in your case a simple get/post request is sufficient.
You can send addition data with request to get the data from endpoint (say id of resource (say person) whose other fields you want to get like name, age, address).
here is link for ajax request in jQuery
here is jQuery parse json parse json in jQuery
So for example:
// let's say when you call this function it will make post request to fixed end point and return data else null
function rvOffices() {
var res = null; // let be default null
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET', // type of request method
dataType: 'text', // type of data you want to send if any.
success: function( data) {
res = $.parseJSON(data); // will do the parsing of data returned if ajax succeeds (assuming your endpoint will return JSON data.)
}
});
return res;
}
// lets call the function
var rvOfficesString = rvOffices();
// print the value returned
console.log(rvOfficesString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can try something like: -
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
dataType: 'text',
success: function(response) {
// get string
window.temp = JSON.parse(response);
}
});

How to retrieve java Set and iterate over the values from response of ajax call?

I have following ajax call
$.ajax({
type: "GET",
url: "../targeturl",
data : postdata,
contentType: 'application/json',
success: function(response, status, request) {
** in response im getting three sets which i wish to iterate
}
last few lines of controller methods are as follows:
JsonWrapper response = new JsonWrapper();
/*some lines to fetch data from db*/
response.addParam("vSet",vSet);
response.addParam("dSet",dSet);
return response;
Since I have never tried this before, please tell me know how to perform this. also let me know if question is not clear enough.
Using JQuery :
$.each(response.vSet, function(index, element) {
//process
});
Using Javascript :
for(var i=0;i<response.vSet.length;i++){
//process
}
If your response is valid Json, you can parse the response using javascripts built in function JSON.parse(). Then iterate over it as you like, depending on how you constructed your json in your response.
$.ajax({
type: "GET",
url: "../targeturl",
data : postdata,
contentType: 'application/json',
success: function(response, status, request) {
var json = JSON.parse(response).
//iterate over json by accessing the indices of json.
for(var i = 0; i < json.length; i++)
{
(..) //do stuff with json[i]
}
//or access json using the key values you specified in your response
json['vSet'] // or json.vSet.
console.log(json) //this will allow you to inspect your response after you parsed it to json.
}

Grabbing JSON data with AJAX

I have a JSON URL that I need to grab the variables from and use them as jQuery stings. I've tried several different approaches and all of them are unsuccessful.
Approach 1
$.getJSON('http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get', function(data) {
alert(JSON.stringify(data))
});
Resilt
I receive an 200 OK message, but I do not get any data returned.
Approach 2
$.ajax({
url:"http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",
dataType:'jsonp',
success:function(data){
var obj = jQuery.parseJSON(data);
alert(obj.title);
}
});
Result
I receive on 200 OK but the obj value is NULL
Approach 3
$.getJSON("http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",function(ajaxresult){
window.artist = ajaxresult.track.artist;
});
Resilt
I receive an 200 OK message, but I do not get any data returned.
You didn't look with attention at the JSON object returned by the service.
What you're looking for is the data property of the returned object which is an array.
Something like this do work :
$.ajax({
url: "http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",
dataType: 'jsonp',
success: function (data) {
console.log(arguments);
alert(data.data[0].title);
}
});
JSFiddle to demo

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);
}
});

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

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()
}

Categories

Resources