0

I'm using the pmxdr library to make a cross domain call (jQuery to php and respond in json). The problem is I can not handle the response properly but if I just print it on HTML is comes as -

{"title":"Mr","first_name":"Shak","last_name":"Mana"}

Here is the code it use

pmxdr.request({
uri     : "http://xxxx/pmxdr/respons1.php",
callback: handleResponse
});

function handleResponse(response) {
if (!response.error) { // request successful
  console.log(response.headers["content-type"]) //works
  console.log(response.data) //works

    for (var key in response.data) {
    alert(response.data[key]); // gives each character :(
}
} else print("Error: " + response.error);
}

on the console I get the above mentioned json but on the alerts I get each character separate popping out. if I use console.log(response.data["title"]) it says undefined. Please tell me what I'm doing wrong.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
chaky
  • 117
  • 2
  • 13

3 Answers3

1

It is because, you are getting a string as response, not a json object. One thing you can do is, make the ajax datatype as json.

dataType : json

Or you can make the string as json object in the client side. you can use parseJSON method for that,

function handleResponse(response) {
response=$.parseJSON(response);
if (!response.error) { // request successful
console.log(response.headers["content-type"]) //works
console.log(response.data) //works

for (var key in response.data) {
alert(response.data[key]); // gives each character :(
}
} else print("Error: " + response.error);
}
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

Try this:

var data = JSON.parse(response.data);

It happens because type of data is string, not json

karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • thanks you so much karaxuna. I'm new to java script. – chaky May 20 '13 at 06:50
  • You are welcome :) I don't know what kind of object it is -> pmxdr.request, but it must have an options where you can write that response data type must be json (as Wings Of Fire suggested). Then you can handle data without parsing to json, it's more comfortable :) – karaxuna May 20 '13 at 06:54
0

In the response function parse it into a JSON Object, i.e JSON.parse(string) should work, I don't know whether it will work in IE, but it works on chrome and Firefox. This should probably do the trick.

kashipai
  • 149
  • 3
  • 13