Retrieve JSON encoded data in AJAX callback - javascript

This is the result when I do console.log(data) within my AJAX callback
{"image":"http://placehold.it/290x120","url":"http://www.google.com.my"}
but when I do data['image'] or data['url'], it can't retrieve the value correctly. I also tried data[0]['image'] to no avail

So I guess data is returned from a ajax request. Your can use the following code to convert string to object:
data = JSON.parse(data);
If you are using jQuery to do the ajax request, you can add dataType: "json" to the ajax option. In this way, there's no need to convert data.

Your data in callback is JSON Object,then
var image=data.image;
var url=data.url;

have you tried data.image and data.url?
also try var x = eval(data);
then x.image and x.url
Be careful of eval() on untrusted data though!!

You need to parse it to Json
var retrieved = ......;
var json = JSON.parse(retrieved);
and then just use:
var image = json.image;
var url = json.url;

Usualy this code from jQuery API's page works great:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.
However, you must remember about the same origin policy as well as the about the correct server response's content type. For json response it should be application/x-javascript or at least text/json.

javascript does not have associative arrays, You should use a javascript object like
var data = JSON.parse(data)
and then you can acces it by
data.image and data.url

If You are getting string as a response then use like below.
var response = '{"image":"http://placehold.it/290x120","url":"http://www.google.com.my"}';
var data = eval("("+response +")");
console.log(data["image"]);
console.log(data["url"]);

Related

How to pass a JavaScript array as parameter to URL and catch it in PHP?

I have an array in JS and I am trying to pass it as parameter to URL and catch it in PHP but I cant get to understand how to do it:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
FYI: I am using windows.fetch for posting.
in PHP:
$trafficFilters = $_GET["trafficFilters"];
$obj = json_decode($trafficFilters);
var_dump($obj);
You are passing the data to php with fetch() intead of ajax, so the alternative of my first answer to do the same with the fetch() is:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var trafficFilterHolderJoin = trafficFilterHolder.join(); // comma-separeted format => "roadworks,snow,blocking"
Now add the trafficFilterHolderJoin variable to the traffic query of the URL of your fetch(), like:
fetch('script.php?traffic=' + trafficFilterHolderJoin)
Then in your php script file you will convert the comma-separeted format to php array format using the explode function:
$traffic = explode(",", $_GET['traffic']);
It's quite simple, you are passing these data to php with ajax, correct?
First of all, you are creating the javascript array incorrectly:
var trafficFilterHolder = [0: "roadworks", 1: "snow", 2: "blocking"];
Don't use brackets to create arrays with keys, use this format instead:
var trafficFilterHolder = {0: "roadworks", 1: "snow", 2: "blocking"};
Now, in the ajax, just add the array in the data:
$.ajax({
data: { trafficFilters: trafficFilterHolder }
});
All demands to the server are executed as an http requests. Ther are two types of HTTP requests - GET and POST.
https://www.w3schools.com/tags/ref_httpmethods.asp
What you're describing is called GET request. With GET request the parameters are passed via the address bar. For making an http request you have two options.
The direct HTTP GET request.
For this you need simply open a new page with
window.location.href = 'http://your_site.com/file.php?name1=value1&name2=value2'
This will open a new page in your browser and pass a request with your parameters.
An Ajax HTTP GET request.
You have a lot of options here:
an old-fashion way with xmlHttpRequest object
a modern fetch API with promises
third-part libraries like jQuery.ajax etc.
AJAX request can send and receive information from the server (either in GET or POST request) without renewing the page. After that the result received can be managed with your javascript application however you want.
Hope, it makes more clear for you. You can search about all this technologies in the google. This is the way how to exchange data from front-end to back-end.
Try using ajax and pass that array and retrieve values at the PHP end.
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
$.ajax({
type: "POST",
url: "test.php",
data: {data : filters},
cache: false,
success: function(){
alert("OK");
}
});

How can I iterate this json?

"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there

Parsing JSON returned via an AJAX POST formating issue

I have a php returning some json in response to a POST request made via an ajax function.
In my php function I format the data like this:
//json return
$return["answers"] = json_encode($result);
echo json_encode($return);
This returns the following string:
answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"
And this is where I am trying to catch it to use the data:
$.ajax({
type: "POST",
url: "http://ldsmatch.com/pieces/functions/question.functions.php",
dataType : 'JSON',
data: dataString,
success: function(data) {
alert(data.answers[0]["aa"]);
}
});
I've been trying to just alert the data so I can visualize it before setting up the vars I need, but am having some trouble formatting it correctly so it is usable.
If I alert data.answers[0] then it just shows me the first character in the string, which is a bracket [ and if i subsequently change the number it will go through each character in the returned string.
I have tried other variations, such as:
data.answers[0]["aa"] (this returns 'undefined' in the alert)
data.answers["aa"] (this returns 'undefined' in the alert)
data.answers[0] (this returns the first character of the string)
I feel like I'm close, but missing something. Any guidance appreciated.
edit:
thanks for all the suggestions. I removed the second json_encode and was able to parse with data.answers[0].aa
success: function(data) {
var json = $.parseJSON(data);
alert(json.answers[0]["aa"]);
}
Use parseJson like this
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
What if you remove double-encoding on PHP side? You've got an object with JSON string instead of object with first property being object itself, or you may explicitly decode "answers" property on client side as it was suggested above.

passing json array ajax

Trying to pass a array using ajax call.
info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info: info, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});
However when i try to catch it on the server side using :
request.getParameter("info"); //Displays null**
Also, if i wish to send an array of arrays ? is it possible?
I tried using serialize however my IE throws error that serialize : object doesnt support this property i Did include jquery lib.
You can use JSON.stringify(info) to create a JSON representation of the object/array (including an array of arrays). On the server side you should be able to get the string via getParameter and then unserialize it from JSON to create constructs JSP can use.
Yes,It is Possible to send arrays.
var info_to_send = ['hi','hello'];
$.ajax({
type: "POST",
data: {info: info_to_send, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});
You can only provide strings in a request url.
You could encode the array like so:
info = JSON.stringify(info);
// results in "['hi', 'hello']"
Then send it to the server, also JSON parse on the server.
You will need to go to http://www.json.org/ to get a Java implementation of JSON parsing.

Array of objects not getting parsed as javascript array of native objects?

I am receiving following data from server
"[{\"role_id\":\"1\",\"name\":\"administrator\",\"created_by_user_id\":\"2\",\"time_created_on\":null,\"is_user_based\":\"0\"},{\"role_id\":\"2\",\"name\":\"manager\",\"created_by_user_id\":null,\"time_created_on\":null,\"is_user_based\":\"0\"}]"
which is simply an array of two objects . Even after setting 'dataType' to json I am not receiving native javascript array inside my success callback function but if I use
$.ajaxSetup({
url:'/public/admin/role/list',
dataType:'json'
});
$.ajax({
success:function(data) {
alert(data[0].name); // alert box pop up as 'undefined '
var data = $.parseJSON(data);
alert(data[0].name) ; //works
}
});
Don't escape the ". They're required for JSON parsing.
[{"role_id":"1","name":"administrator","created_by_user_id":"2","time_created_on":null,"is_user_based":"0"},{"role_id":"2","name":"manager","created_by_user_id":null,"time_created_on":null,"is_user_based":"0"}]
You have a trailing comma when setting dataType in your ajaxSetup method:
dataType:'json',
^
Also I hope those \ in the JSON you have shown here are not part of the actual response from the server. The response should look like this:
[{"role_id":"1","name":"administrator","created_by_user_id":"2","time_created_on":null,"is_user_based":"0"},{"role_id":"2","name":"manager","created_by_user_id":null,"time_created_on":null,"is_user_based":"0"}]

Categories

Resources