2

I am using a PHP script to create JSON data. It looks like this:

{"Id":0}

Now if I put that into a file and then load it using ajax it's fine. But if I request this from the PHP script I get

parsererror | SyntaxError: Unexpected token ILLEGAL

Here is the code that I am using to load the JSON from the PHP:

$.ajax({
                    url: 'check.php',
                    data: {
                        username: 'LOL',
                        password: '1234'
                    },
                    dataType: 'json',
                    type: 'POST',
                    success: function(data) {
                        $('#result').html('#Id=' + data.Id);
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        $('#result').html(textStatus + ' | ' + errorThrown);
                    }
                });

Here is the PHP code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<?php

    echo '{"Id":0}';

?>

Any ideas?

3
  • 1
    How are you requesting it from PHP? Commented Jun 13, 2011 at 0:38
  • @Pradeep: Edit done @ultimatebuster: Yes I know thank you Commented Jun 13, 2011 at 0:40
  • PHP error messages usually state the file and line the error occurred Commented Jun 13, 2011 at 0:41

3 Answers 3

7

Doctypes belong on HTML documents, not JSON.

Try something like this in your PHP file (and only this)

<?php
header('Content-Type: application/json');
?>
{"Id":0}

Given what you have posted, I can't see any reason to even involve PHP. I'm guessing you've only posted a very simple example. Should it become more complex, involving server-side processing, data retrieval, etc, use PHP's json_encode(), for example

<?php
header('Content-Type: application/json');
$data = array(
    'Id'  => 0,
    'foo' => $someOtherComplexVariable
);
echo json_encode($data);
exit;
Sign up to request clarification or add additional context in comments.

1 Comment

@Joaquín was adding an example as you commented :)
1

In your error function use this and check what data is being returned from the server.

error: function(jqXHR, textStatus, errorThrown) {
   $('#result').html(textStatus + ' | ' + errorThrown + ' | ' + jqXHR.responseText);
   alert(jqXHR.responseText);
}

You will know where exactly it is going wrong. The data type and the special characters. Set the content type to application/json and encode your json string using json_encode(). Also, you don't need the doctypes.

Comments

0

use jquery's parseJSON
e.g.

success: function(data) {
    data = jQuery.parseJSON(data);
 $('#result').html('#Id=' + data.Id);
}

1 Comment

That will cause more errors since his options have dataType: 'json' in it. data is already parsed (or failed to, in which case parseJSON will fail again).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.