0

I send an Ajax call to a PHP file, Then an array is returned.

I want to check the values of the returned data.

Here is the Javascript/jQuery code:

$.ajax({
    url: "file.php",
    type: "POST",
    data: {'num': 12},
    dataType : "json",
    success: function(data){
        JSON.parse(data);
        console.log(data.status);
    }
});

PHP code:

$status = 1;
$msg = 'Test message';
$response = array($status, $msg);
echo json_encode($response);

But I'm getting an error JSON.parse: unexpected non-whitespace character

4
  • 2
    Remove JSON.parse(data) from your JS code. jQuery will already have deserialised it for you Commented Oct 31, 2019 at 14:02
  • console.log(data.status); returns undefined Commented Oct 31, 2019 at 14:16
  • What does console.log(data) output? Commented Oct 31, 2019 at 14:18
  • 1
    @RoryMcCrossan It was an incorrect bit of PHP creating the response. Fixed it in my answer after the OP pointed it out Commented Oct 31, 2019 at 14:20

1 Answer 1

4

You used dataType : "json", in the AJAX parameter list, which tells jQuery to expect JSON and do the Parse internally for you.

So remove the JSON.parse(data); and all should be well

You will also have to change the PHP to make the returned data appear in the right place like this

$response = array('status' => $status, 'message' => $msg);
Sign up to request clarification or add additional context in comments.

2 Comments

But console.log(data.status); returns undefined
See amended response from the PHP

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.