0

I have this encode in JSON format as returned data:

{
    "error": {
        "msg":"Concurrent verifications to the same number are not allowed",
        "code":10
    }
}

and I want to access msg so I wrote the javascript as:

$("#buttonPhoneSubmit").click(function(e) {
    $("#verifyForm").show();
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: './process.php',
        data: $('form').serialize(),
        datatype:'json', 
        success: function (data) {
             $('#error_message').html(data.error.msg);
        }
    });

but it said the data is undefined. Can someone tell me what's wrong with the code?

Thanks!

5
  • Then you need to check process.php for what it is returning and also check the network tab of your browser to know how the API is responding Commented Sep 4, 2018 at 6:53
  • 1
    datatype to dataType Commented Sep 4, 2018 at 6:53
  • @Roy - Or better yet, the server code should set the correct Content-Type. Using dataType is very much a second-best approach. Commented Sep 4, 2018 at 6:56
  • by default jQuery will parse JSON responses into javascript objects on ajax. Are you sure that your "process.php" is returning properly? Also rename datatype to dataType Commented Sep 4, 2018 at 6:56
  • @MKougiouris - Only if the response is correctly identified as JSON. Commented Sep 4, 2018 at 6:59

1 Answer 1

2

As Roy said, you have datatype: 'json' instead of dataType: 'json'. So I suspect jQuery isn't parsing the JSON for you.

While you could change it to dataType: 'json' instead, the better approach is to update the PHP file to send the Content-Type: application/json header with the response:

// In the PHP, prior to sending the body of the response
header('Content-Type: application/json');

...and remove datatype: 'json' from your ajax call. jQuery will see the content type and parse it for you, at which point your code should work (assuming the page return returns the JSON you've quoted).

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

1 Comment

Yes as I just copied code from some tutorials, may be missing the <pre>header('Content-Type: application/json'); </pre> bit in the php file and after the changes, it works perfectly! Thanks for you guys help. :)

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.