15

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?

Muhammad Usman
  • 12,439
  • 6
  • 36
  • 59
Skylineman
  • 566
  • 3
  • 8
  • 19

6 Answers6

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.

A.L
  • 10,259
  • 10
  • 67
  • 98
Wrong
  • 111
  • 1
  • 10
3

Try

 alert( jqXHR.responseText);

in your error function

Alon Eitan
  • 11,997
  • 8
  • 49
  • 58
  • 1
    I think ajax_utf.php return html code and not json. Do you use json_encode() in youp php script? – Alon Eitan Sep 17 '11 at 19:09
  • and maybe you also echo html code during the execution of the script? Does your php scrit include any html tags? – Alon Eitan Sep 17 '11 at 19:15
  • 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); – Skylineman Sep 17 '11 at 19:23
  • Try to alert(data.msg), also try to add changeteamadmin to the data: { a: 'changeteamadmin', admin : $('#admin-id-'+id).val() } – Alon Eitan Sep 17 '11 at 19:32
  • and dont forget in you php script: if ($_POST['a'] == 'changeteamadmin') { ..... } – Alon Eitan Sep 17 '11 at 19:34
  • 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.'; } } } – Skylineman Sep 17 '11 at 19:52
  • 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); – Alon Eitan Sep 17 '11 at 20:09
  • I have 5.3.5. Could you find the problem, if I send you the source files? – Skylineman Sep 17 '11 at 20:20
  • before the line "if (empty($_POST['admin'])) {", try to add "$return['msg'] = "";" – Alon Eitan Sep 17 '11 at 20:48
  • and also change if ($_GET['a'] == 'changeteamadmin') { --- to if ($_POST['a'] == 'changeteamadmin') { – Alon Eitan Sep 17 '11 at 20:54
  • sorry, no change, still no response. :( – Skylineman Sep 17 '11 at 21:02
  • so in the ajax data, change the a : 'changeadmin', to --------- a : 'changeteamadmin', – Alon Eitan Sep 17 '11 at 21:27
  • I've changed before trying to run it – Skylineman Sep 17 '11 at 21:50
  • Or could you show or write me a working one for jQuery, and I'll change it for myself. – Skylineman Sep 17 '11 at 22:01
  • I got same problem in MVC ajax call. Problem waw path to controller was not exact. – Baqer Naqvi Oct 21 '15 at 12:52
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.

Andrew Killen
  • 1,756
  • 24
  • 24
1

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

Sudhir
  • 766
  • 8
  • 17
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);
            }
        });
rrr_2010
  • 87
  • 5
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.

Digitum
  • 1
  • 1