1

Can't work this one out for the life of me, hopefully I am not doing something stupid but why this is not working is not clear to me.

I have a basic HTML page with a JQuery script that sends the following AJAX call to a PHP script within the same directory.

JQuery:

// Sends the AJAX request
            $.ajax({
              type: "GET",
              url: "process.php",
              dataType: "json",
              success: function(data) {
                console.log(data);
              }
            });

PHP:

<!-- Ajax request handler -->
<?php 

echo json_encode(array('message' => 'AJAX call received'));

exit();

?>

The AJAX call is being made successfully as after debugging it in the console it's status code is 200 and statusText 'ok'. However, I simply cannot get the returned JSON message to show up in the console as it should.

I have double checked the URL and that's fine.

This is the response I get in the console using Jeff Hatz's AJAX Debugger Chrome Extension:

Console Screenshot

Any ideas folks?

14
  • 1
    does a null value or anything get output to console? Commented Aug 29, 2018 at 14:10
  • is the php from your process.php file ? Commented Aug 29, 2018 at 14:10
  • you could try adding error: function (response) {console.log(response);} Commented Aug 29, 2018 at 14:11
  • 1
    If your PHP is outputting <!-- Ajax request handler --> before the json, then the ajax json parser will not work. You must only and truly return a pure json string from your php when using dataType: 'json'. Commented Aug 29, 2018 at 14:44
  • 1
    Problem solved. I'm an idiot. I had a comment outside of the PHP tags that was obviously causing the problem as @IncredibleHat pointed out. Commented Aug 29, 2018 at 15:20

1 Answer 1

2

You need to remove this line from the top of your PHP:

<!-- Ajax request handler -->

As when you make a ajax call with dataType: 'json' it is not going to parse the response (at all) and then when you do a console.log(data); it is simply empty, no console log.

When you do remove that line, you should instead receive in your Network tab Response:

{"message":"AJAX call received"}

Which then in a console.log(data); you should see:

Object {message: "AJAX call received"}
Sign up to request clarification or add additional context in comments.

1 Comment

Then onward to actually use the message value itself, you use normal js objection notation with data.message....

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.