How to get a value from Json result - javascript

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

Related

How to tell JavaScript that my variable is an array and not a string?

I'm using flask and my backend returns to AJAX a response in the form of a python list, and then JavaScript understands it as a string, but that's a problem because I have to iterate over that list.
All i could find on the internet is how to check the type of a variable, but couldn't find any method (which in python is pretty straightforward) to change it
The Array.isArray() method determines whether the passed value is an Array or not.
var someNumbers = [1,2,3];
console.log( Array.isArray( someNumbers ) );
and if it is an array it will return
true
Check this link to know more about Array.isArray
If your response is a string, you can use JSON.parse to turn it into an JS Object/Array.
var response = someAjaxStuff(...);
// response is a string
response = JSON.parse(response);
// now reponse is an Object/Array
If you use AJAX with jQuery, you can also use dataType:
$.ajax({
url: 'https://example.com/api/somejson',
dataType: 'json',
method: 'get',
success: function(res) {
// console.log res will be an object/array here.
}
});
But if you're writing your own API, I suggest you have to add the right header to tell browser that it is a JSON format instead of string.
For flask you can use jsonify (reference):
return jsonify(somedict)

jQuery.getJSON always returns empty object

I've been looking for a way to include an object from a JSON file, and I've found several pages summarizing how to use $.getJSON(), and even a few answers here, but none have worked. Some have suggested I do it this way:
var json;
$.getJSON("dir/1.json", function(response){
json = response;
});
And some have suggested it this way:
var json = $.getJSON("dir/1.json");
Neither of these work. When I try to call a property of json, such as json.title, it just gives me an error saying the variable is undefined. No one else seems to be having this problem, so what am I doing wrong?
Try using this:
var json = $.getJSON( "dir/1.json" )
.done(function( response ) {
json = response;
console.log( "json variable ready" );
})
.fail(function() {
console.log( "error" );
});
Update
The response object returned by $.getJSON() implements the promise interface, giving it all the properties, methods, and behavior of a promise. So json isn't ready until a response is returned or the done function is fired.
The response is deferred. At the time you're reading the variable, the response likely hasn't responded yet. Try accessing the variable inside the function callback, right after json = response;

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

Read json object

I'm having a problem reading JSON; my PHP server encodes an object created with the stdClass, then sends this object on my Ajax asynchronous script. I tried to alert the object and the
representation is like this:
alert(prova) //Gives {"idProva":"3","name":"test"}
Now if the variable name is prova, how can I read the value 3?
I tried using prova.idProva, but it doesn't work.
try parsing json into a object
var json = '{"idProva":"3","name":"test"}',
obj = JSON.parse(json);
alert(obj.idProva);
i hope this will help
In ajax all add dataType:'json'
$.ajax({url: '',
dataType: 'json',
type: 'GET',
success: function (prova) {
alert(prova.idProva);
}
);
This may help you,
var data = {"idProva":"3","name":"test"}
console.log(data['idProva']);

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

Categories