Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.ajax() v1.5 returns "parsererror" for json data

I have this function for getting a server id from a list. The function always returns "parsererror". I have looked at the JSON data returned but I cant seem to get it working, since jQuery have rewritten the ajax in v1.5.

function server_id()
{
    $.ajax({
        type: "GET",
        url: "http://localhost/server_list.php",
        dataType: "json", 
        success: function(data, status) {
             alert(status + "\n\n" + data.server_id);
        },
        complete: function(data, status){
                  alert(status);
        }
    });

}

server_list.php

    header('Content-type: application/json');

    $output['server_id'] = '123';
    print json_encode($output);

In firebug Net >> XHR it reads it as JSON as it brings up the tab and the Response tab shows what is below.

{"server_id":"123"}

I have also tried setting the content type header like below but having no luck.

Content-type: application/json

UPDATED

I only get "parsererror" if the validation plugin is loaded from http://bassistance.de/jquery-plugins/jquery-plugin-validation docs.jquery.com/Plugins/Validation v1.7.

If you add the plug jquery automatically adds the jsonp callback to the query string even when you set to false or dont include the parms for jsonp. Very Strange

Any ideas on how to fix?

Thanks

like image 435
ClaireTaylor Avatar asked Feb 11 '11 12:02

ClaireTaylor


People also ask

Does AJAX return JSON?

You couldn't directly return an array from AJAX, it must have converted in the valid format. In this case, you can either use XML or JSON format. In the tutorial demonstration, I will return an array of users from AJAX, while return converts the array into JSON format using the json_encode() function in the PHP.

What is Parsererror in AJAX?

The reason why this parsererror message occurs is that when you simply return a string or another value, it is not really Json , so the parser fails when parsing it. So if you remove the dataType: json property, it will not try to parse it as Json .

What does AJAX request return?

The $.ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option.


1 Answers

The simple solution here seems to be that jQuery 1.5 is not compatible with 1.7 of the validation plugin. Downgrading to jQuery 1.4.x (or otherwise patching or removing the validation plugin code as philhag suggested) solves the issue.

Huge thanks to those on this thread who identified the conflict. It saved me a bunch of headaches having to debug the jQuery code.

like image 180
skylar Avatar answered Nov 02 '22 07:11

skylar