Accessing values of a JSON-encoded object - javascript

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

Related

Get json data from server

I am trying to get a json array of ints from a server by sending the server a get request. When I run the code below the server receives the request. How can I print the data the server sends back? The second alert() doesn't show.
$(document).ready(function(){
alert("READyS");
$("button").click(function(){
$.getJSON("http://localhost:8080/Data/", function (data) {
alert("data recieved");
});
});
});
Since you are using jQuery you can use this:
$("button").click(function(){
$.get( "http://localhost:8080/Data/" )
.done(function( data ) {
alert( "Data Loaded: " + data );
});
});
Obs.: Please be more specific about what button is.
If still don't work, paste your html here
You can use a callback function passed to success state of the AJAX request. This way you're using the async nature of the request, which doesn't block the browser call stack while it's waiting for requested data and You're getting the result printed to the page. This is just a single p element that has all the request's information inside of it, so it will work if it's just a string. If it's an array of objects or something like that then you can create a map function with printData function inside it to loop through all of the downloaded objects.
function printData(passedData) {
jQuery('<p/>', {
id: 'foo',
text: passedData
}).appendTo('body');
}
function testAjax(handleData) {
$.ajax({
url:"http://localhost:8080/Data/",
success:function(data) {
handleData(data);
}
});
}
testAjax(printData);

PHP json_encode is returning as array string, but is not converting to array in JavaScript properly

I make a $.post request to submit data and return invalid data. Here is the $.post request:
$('#submitAll').click(function(){
$.post("php/entries/submitAndReload.php", {array : dataObject.dataArray}, function(data){
alert(data); // alerts: "[[“0”, “0”,””,””, “0”, “0”, “0”, “0”,”No Style”]]"
dataObject.dataArray = data;
$.post("php/entries/stageArea.php", {array : dataObject.dataArray}, function(data){
$('#stageArea').html(data);
});
});
});
dataObject.dataArray is a double array and alert(data) alerts what looks like the proper format for the subsequent $.post request, but the output from the 2nd $.post request looks like I pass in the following array:[[ "[" ]]. The first field gets a "[" and no other fields get data.
I'm not sure what's going on here and how to properly store the returned data into dataObject.dataArray
What's going on here?
Correct this line:
dataObject.dataArray = data;
To this:
dataObject.dataArray = JSON.parse( data );
You need to parse JSON, untill parsing it is just a string.
Add dataType argument to $.post.
When set as 'json' jQuery knows to parse it to object/array from json string
$.post(url, postData, function(data){
// handling code
alert($.type(data)); //"array"
},'json');
If you set proper content Type header at server also it helps
Reference: $.post docs

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

How to get a value from Json result

This is the json result I get from my controller
{"data":"Sunday"}
The data can say any day of the week (Sunday, Monday, etc...)
On success I want to do this in ajax call
success: function(Response){
var myresponse = Response.data;
alert(myresponse);
}
However, it gives me undefined.
If you are sure that you are getting a JSON response from the server, you can make use of the Ext.JSON class to decode the JSON.
You can use the decode() method to convert a string to an object. Then you should be able to easily access it.
Example:
var jsonObject = Ext.JSON.decode(Response.responseText);
var myData = jsonObjet.data;
If you are using jQuery to load this string you could just use $.getJSON which will automatically parse the string and pass the object as the return value to the 'success' function.
try to use a
console.log(Response);
to check the content of Response
It might be considering your response to be a string. I would do something like this:
success: function(Response){
alert(typeof Response);
var myresponse = Response.data;
alert(myresponse);
}
If it tells you that Response is string, you need to make sure that your framework knows you are getting back JSON. For instance with jquery it might be $.getJSON().

Javascript: How to tell whether AJAX response is JSON

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

Categories