jquery throws SyntaxError with valid JSON response

So I have an ajax function communicating with a php file returning json_encode.

The ajax function:

$.ajax({            
        type: 'POST',
        data: sendData,
        dataType: 'json',
        mimeType: "application/json",
        url: 'request.php',                 
        success: function(data){
            return data;
        }
    });

sendData is something like this:

{ 'action': 'do_stuff', 'id': 5 }

And the result is

{"affected_rows":1,"insert_id":0}

I have checked for weird termination characters or padding in the result and found nothing. Interestingly enough, the error that is being thrown is "Uncaught SyntaxError: Unexpected token o", which is strange because the result does not begin or end with an o, and the only o is in the middle.

I've also tried not defining the data or mime types and manually parsing the json with both JSON.parse(data); and jQuery.parseJSON(data); with no success.

If it helps, request.php returns its data like this:

        $a = $_POST[action];
        $result = call_user_func_array($a, $_POST);
        if($result){
            echo json_encode( $result );
        }else{
            echo json_encode( 'There was an error processing your request (Error: '.get_error_id($a).')'  );
        }

Answers


The error message Uncaught SyntaxError: Unexpected token o seems unrelated with the JSON being valid or invalid.

Are you sure there isn't elsewhere another AJAX callback configured to run? (At AJAX global settings?)

I am supposing the error indicates malformed JavaScript (not invalid JSON)...


Try to put :

header("Content-Type: text/javascript");

Before :

if($result) {

Need Your Help

Call has been made on garbage collected delegate in C#?

c# .net

I have been using this key hook script i found but I continue to get an error after a few seconds of using it in my program. The error says.. A call has been made on a garbage collected delegate '

How to interface Ruby with Mercurial (Python)?

python ruby mercurial language-binding

I'm hoping to integrate Mercurial into my Rails site. I want to run basic commands like status, summary, log, and maybe even clone. I'd like to interface directly with the Mercurial libraries and a...