jQuery AJAX - Unexpected token + parsererror
Asked Answered
R

6

16

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?

Retread answered 17/9, 2011 at 18:50 Comment(4)
What happens if you call ajax_utf.php?a=changeteamadmin directly outside of your javascript?Hobnail
It shows a message what I sat up in the PHP file.Retread
can you check if the json returned is valid? you can check at www.jsonlint.comPhonotypy
It doesn't like jQuery codes .. :(Retread
J
7

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.

Juncaceous answered 6/7, 2012 at 16:38 Comment(2)
Do you have any idea how to solve this problem in asp.net ?Corselet
To solve this is ASP.NET (webforms) you can add the [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attribute to your method.Hearthside
O
3

Try

 alert( jqXHR.responseText);

in your error function

Olid answered 17/9, 2011 at 19:0 Comment(16)
it says: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />Retread
I think ajax_utf.php return html code and not json. Do you use json_encode() in youp php script?Olid
and maybe you also echo html code during the execution of the script? Does your php scrit include any html tags?Olid
Yes. Now I found, I made a new php, with only this one code. Now I don't get error, but I don't get any response to my site. The javascript code: "$('#ta-modarea-'+id).text(data.msg).fadeIn('fast');" And the PHP: $return['msg'] = 'something here'; echo json_encode($return);Retread
Try to alert(data.msg), also try to add changeteamadmin to the data: { a: 'changeteamadmin', admin : $('#admin-id-'+id).val() }Olid
and dont forget in you php script: if ($_POST['a'] == 'changeteamadmin') { ..... }Olid
I tried some things. It has problem with an IF. From the "PROBLEM FROM HERE" if (empty($_POST['admin'])) { $return['msg'] = 'Hibás GAMER ID.'; } else { $do->mysqlSelect('user', 'icl_users', 'WHERE id = "'.$_POST['admin'].'" LIMIT 1'); $user_nr = $do->msS('user', 'nr'); $user_team = $do->msS('user', 'team_id'); if ($user_nr == 0) { $return['msg'] = 'Hibás GAMER ID.'; } else { //PROBLEM FROM HERE if ($user_nr == 0) { $return['msg'] = 'Módosítás sikeres.'; } else { $return['msg'] = 'A felhasználó már egy másik csapatban van.'; } } }Retread
I don't know what type of problem do you have, but if your php version is 5.4.0 , you can try to add JSON_UNESCAPED_UNICODE: echo json_encode($return,JSON_UNESCAPED_UNICODE);Olid
I have 5.3.5. Could you find the problem, if I send you the source files?Retread
before the line "if (empty($_POST['admin'])) {", try to add "$return['msg'] = "";"Olid
and also change if ($_GET['a'] == 'changeteamadmin') { --- to if ($_POST['a'] == 'changeteamadmin') {Olid
sorry, no change, still no response. :(Retread
so in the ajax data, change the a : 'changeadmin', to --------- a : 'changeteamadmin',Olid
I've changed before trying to run itRetread
Or could you show or write me a working one for jQuery, and I'll change it for myself.Retread
I got same problem in MVC ajax call. Problem waw path to controller was not exact.J
G
2

If you have tried setting the header content type and are still getting the error. It is my expectation that the server is replying with a fault from your server side code. Usually when a debug message is given it is in pure HTML not JSON thus the unexpected token.

The quickest way to debug this is to set the DataType of the HTML instead of JSON so that you can see whatever output there is from the server, not just JSON formatted data.

Once you have seen the error that is being produced by your server side code and fixed it, you can then return to being a DataType of JSON.

Gamester answered 1/7, 2013 at 12:3 Comment(0)
R
1

contentType: "application/json; charset=utf-8",

Repartition answered 28/10, 2013 at 22:1 Comment(0)
L
1

Try code below, but if you receive an error like "Unexpected token <", you need to check your php file - "ajax_utf.php" and check what is returned in browser (Chrome) View->Developer->Developer Tools, Network tab -> XHR.

enter image description here

         $.ajax({
                type: 'post',
                url: postLink,
                dataType: 'json',
                data: postData,

            beforeSend: function (x) {
                if (x && x.overrideMimeType) {
                    x.overrideMimeType('application/json;charset=UTF-8' );
                }
            },
            success: function (result) {
                //console.log(result);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(arguments);
            }
        });
Lei answered 8/4, 2016 at 1:5 Comment(0)
C
0

It could be an issue with missmatching PHP associative/numeric arrays and Javascript objects.

Try this:

$data = new Array();
$data['test'][] = "Row 1";
$data['test'][] = "Row 2";
echo json_encode($json, JSON_FORCE_OBJECT);

This should force json encoder to always encode to objects instead of numeric arrays and may solve the problem.

Cyprian answered 10/2, 2013 at 20:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.