-4

I'm having an issue. I have a json_encode array in php. With ajax, I get back in my javascript script.

php

<?php
$code = 'xyz';
$email = 'xyz@gmail.com';
$back = array();
array_push($back, array("code" => $code,"email" => $email));
echo json_encode($back);
?>

ajax callback function

function(data){
alert(data);
alert(data[0].code);
}

When I try to alert data, I get [{"code":"xyz","email":"xyz@gmail.com"}]

Now when I try to alert the code (or the email) it says undefined.

Can you help me alert data[0].code properly ?

Jason Krs
  • 704
  • 2
  • 9
  • 30
  • Your response probably isn't being parsed as JSON. Set `dataType: "json"` in your ajax call. Or update your question showing your full ajax code if that doesn't work. – jszobody Jun 17 '16 at 14:48
  • Also, why even nest that array in the first place? It would simplify thing if you just did `$back = ["code" => $code,"email" => $email];` – jszobody Jun 17 '16 at 14:49

3 Answers3

3

In your ajax options set dataType: "JSON"

Boris Savic
  • 781
  • 5
  • 9
0

You need to parse it

function(data){
    var obj = JSON.parse(data[0]);
    alert(obj.code)
} 
0

its working ,i am tried in jsfiddle

var data=[{"code":"xyz","email":"xyz@gmail.com"}]
alert(data);
alert(data[0].code);

i got in alert xyz

Maharajan
  • 178
  • 9