user470760
user470760

Reputation:

JSON Stringify & AJAX parse errors

I have been at this for hours trying everything I could possibly find suggested on the web, however it continues to fail. When I encode function parameters with JSON.stringify and then pass it to my PHP handler via AJAX, I am getting an Alert pop-up saying parsererror.

It is apparently an issue within the Javascript but I cannot determine where at this point.

Can anyone perhaps spot what I am doing wrong here?

            // JSON Encode to pass via AJAX to PHP
            var params = { "id": player };
            var params2 = JSON.stringify(params);

            // {"id":"939952da-23df-4ff1-b66c-61018b621645"}
            console.log(params2);

            cellOptions.innerHTML = "<button onclick='sendAction(\"kickPlayer\"," + params2 + ")'>Kick</button>";

AJAX

function sendAction(cmd, params)
{
    $.ajax({
        type: "POST",
        url: "handler.php",
        data: { 'action': cmd, 'params': params },
        dataType: 'json',
        success: function(data)
        {
            if (data['status'] == 'failed')
            {

            }
            else if (data['status'] == 'success')
            {

            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        { 
            alert("Status: " + textStatus); alert("Error: " + errorThrown); alert("Message: " + XMLHttpRequest.responseText);
        }
    });
};

Upvotes: 1

Views: 3271

Answers (2)

laruiss
laruiss

Reputation: 3816

By coding this :

dataType: 'json',

you tell jQuery to expect a JSON String in the response (from the backend, i.e. our PHP code). So on the callback, jQuery parses the string, and since you are not receiving a valid JSON string from the backend, it fails to parse it, and throws this parser error.

Edit: see jQuery documentation:

 dataType (default: Intelligent Guess (xml, json, script, or html))

Type: String The type of data that you're expecting back from the server.

From http://api.jquery.com/jquery.ajax/

Upvotes: 3

bhspencer
bhspencer

Reputation: 13570

Do not stringify the params before you pass them to your sendAction function.

Instead Stringify the entire object you send to the server. e.g.

data: JSON.stringify({ 'action': cmd, 'params': params }),

Upvotes: 0

Related Questions