2

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.

3
  • Are you also using jQuery? Can you show some more of the call in ajax, please? Commented Mar 22, 2014 at 4:53
  • $.ajax({ type:"POST", url:"php/registerDetails.php", data:data, success:function(data){ var currentData=data; console.log(currentData); var s=currentData.currentId; console.log(s); }, error:function(jqXHR, textStatus, errorThrown){ console.log(errorThrown); }, }); Commented Mar 22, 2014 at 4:55
  • 1) Open the ajax url in browser and make sure it has only json string and no other extra characters. 2) Use a content-type:json header in php 3) Specify dataType as json in jquery request Commented Mar 22, 2014 at 4:58

2 Answers 2

1

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.

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.