0

My PHP script is returning a JSON object that I am receiving in AJAX call.

$arr[0] = $resp;
            $arr[1] = $e;
            return json_encode($arr);

Now in my AJAX call , I try to get the value but all I get is "/" or "'" .

I am doing this in AJAX.

dd = JSON.stringify(x.responseText); //this is the response from PHP which is correct I have verified.
alert(dd[0]); //supposed to output $arr[0] but it doesn't

Am I doing something wrong here?

I have seen this on SO

3
  • @u_mulder the problem is not about alert or console.log or printing, its about getting correct data. Commented Jan 23, 2016 at 13:18
  • 1
    Console.log and see what you have in dd. JSON.stringify btw makes json string from it's argument. Maybe you need JSON.parse? Commented Jan 23, 2016 at 13:18
  • @u_mulder yes JSON.parse worked :) thanks Commented Jan 23, 2016 at 13:26

1 Answer 1

0

I think the JSON.parse solve your problem.

The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing.

Examples

JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null

Using the reviver parameter

JSON.parse('{"p": 5}', function(k, v) {
  if (k === '') { return v; } // if topmost value, return it,
  return v * 2;               // else return v * 2.
});                           // { p: 10 }

JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', function(k, v) {
  console.log(k); // log the current property name, the last is "".
  return v;       // return the unchanged property value.
});

Ref:

JSON.parse()

JSON Example - Object From String

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.