Mohaideen
Mohaideen

Reputation: 303

How to get json value

I am using jquery ajax for calling PHP

PHP

$response = array('isSuccessful'=> true , 'currentId'=> $currentId);
$response = json_encode($response);
echo $response;

Success() in ajax

success:function(data){
                var currentData=data;
                console.log(currentData);
                var s=currentData.currentId;
                console.log(s);
            }

Output is

{"isSuccessful":true,"currentId":13} 
undefined

What is the mistake i made.

Upvotes: 2

Views: 61

Answers (2)

Francisco Presencia
Francisco Presencia

Reputation: 8841

You are missing the dataType in the ajax call, as can be read in the ajax documentation.

$.ajax({
  type:"POST",
  url:"php/registerDetails.php",
  data:data,
  dataType:"json",
  success:function(data){
    var currentData=data;
    console.log(currentData);
    var s=currentData.currentId;
    console.log(s);
    },
  error:function(jqXHR, textStatus, errorThrown){
    console.log(errorThrown);
    },
  });

This is normally not required (for example, if you set the headers and let jquery guess it), but I'd recommend making sure that jquery knows the data it's receiving and handling the error if any than relying on a script on another page with another language to make sure of your data integrity.

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76666

You also need to send the correct headers (which in this case is application/json):

$response = array('isSuccessful'=> true , 'currentId'=> $currentId);
$response = json_encode($response);
header('Content-Type: application/json');
echo $response;

Or if you want to parse it yourselves, then you can use $.parseJSON(data), but make sure to manage the error thrown if the parsing fails.

Upvotes: 1

Related Questions