1

Can someone tell me why in the world I keep getting a parseerror in the console with the following code?

$.ajax({
    url : "file.php",
    data : data,
    dataType : "json",
    success : function (request) {
        console.log("success");
    },
    error : function (request, error) {
        console.log(error);
    }
});

I have validated my JSON with jsonlint.com and it's Valid.

The Response Headers being returned in the Net tab of Firebug are:

Content-Length 19

Keep-Alive timeout=5, max=96

Connection Keep-Alive

Content-Type application/json

5
  • What do you see in Firebug's Net tab? Commented Dec 22, 2011 at 21:59
  • Is there more detail in the error? Commented Dec 22, 2011 at 22:00
  • 1
    The code you have posted does not throw any errors, what is the exact error you are getting? Perhaps the name or value of the form input (I'm guessing) contains invalid characters. Commented Dec 22, 2011 at 22:03
  • What version of jQuery are you using? Commented Dec 22, 2011 at 22:13
  • Have you tried changing the dataType to text? You should then be able to console.log the return data. Commented Dec 22, 2011 at 22:41

2 Answers 2

2

This is how you can send json from PHP

$response = array("title" => "One");

echo json_encode($response);

If { "title": "One" } is the response, Content-Length of response should be 18, but from your description I can see that it is 19. So something is wrong in the response json string, please check it.

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

2 Comments

From the screenshot what I can understand is that response is json but string encoded in json. Usually this happens when we do like this echo json_encode('{ "title": "One" }'); Either you can set content type as json and use echo '{ "title": "One" }; or make the response object and encode it json and use echo like this $response = array("title" => "One"); echo json_encode($response);
Thanks for the help. It turned out there was an error in my PHP file.
0

It seems possible that the name or value of this may have invalid characters. Instead of concocting your own data string how about letting jQuery do it for you:

data  = $this.serialize();

3 Comments

@Zoolander I know you posted code that declared dataType : 'json' but I just have to check, you're not setting dataType : 'jsonp' are you? Because the response would almost certainly create a parse-error if the dataType is not properly set...
@Zoolander Maybe set contentType: "application/json; charset=utf-8"?
@Zoolander Hows about: $.getJSON('file.php', data, function (response) {console.log('success');});?

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.