jQuery AJAX - Unexpected token + parsererror

Skylineman picture Skylineman · Sep 17, 2011 · Viewed 41.8k times · Source

I wrote a script using jQuery and AJAX today, and I get some errors...

The script:

function changeAdmin(id) {
$(document).ready(function() {
    $('#ta-modarea-'+id).fadeOut('fast');
    $('#ta-m-loading-'+id).fadeIn('fast');

    $.ajax({
        type: 'POST',
        url: 'ajax_utf.php?a=changeteamadmin',
        dataType: 'json',
        data: {
            admin : $('#admin-id-'+id).val()
        },
        success: function(data) {
            $('#ta-m-loading-'+id).fadeOut('fast');
            $('#ta-modarea-'+id).text(data.msg).fadeIn('fast');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $('#ta-m-loading-'+id).fadeOut('fast');
            $('#ta-modarea-'+id).text('HTTP Error: '+errorThrown+' | Error Message: '+textStatus).fadeIn('fast');
        }
    });

    return false;
});
}

After the run, I get this error message: HTTP Error: SyntaxError: Unexpected token < | Error Message: parsererror

Could you help me, what should I do?

Answer

Wrong picture Wrong · Jul 6, 2012

You need to send an application/json header via PHP , like this:

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

That's because jQuery sends an Accept header (application/json, text/javascript), and this is the cause of parseerror triggered by jqXHR.