ACs
ACs

Reputation: 1445

JQuery gives JSON syntax error when using PHP's json_encode

I have an application that uses JQuery $.ajax to send JSON encoded data to server where I process it and then send back the results also JSON encoded. The problem is that JQuery gives a parse error when I want to process the response. (As if PHP's json_encode function outputs an invalid JSON format). Here comes the code:

The Javascript code:

$.ajax({
     type: 'POST',
     url: URL+'pages/processListUIAjaxRequest',
     data:{filters: filters, rebuild_params: $('#rebuild_params\\['+unique+'\\]').val()},
     dataType: 'json',
     success: function(response){
          alert(response);
     },
     error: function(request, status, error){
          alert('Unable to update table contents');
          console.log(request);
          console.log(status);
          console.log(error);
     }
});

This is a piece of the PHP code which outputs the response:

$response->addResult($uFilters);
header('Content-Type: application/json');
$response->toJSON(true);

The $uFilters is a simple array, and the toJSON method of the $response object is here:

public function toJSON($output = false){
        $out = array();

        if($this->hasErrors()){
            $out['has_error'] = true;
            $out['errors'] = $this->getErrors();
        } else $out['has_error'] = false;
        $out['result'] = $this->_result;

        if($output){
            echo json_encode($out);
        }else{
            return json_encode($out);
        }
    }// toJSON

Every time I run the code i get the 'Unable to update table contents', and on JavaScript console I have:

'SyntaxError: JSON.parse: unexpected character'

despite I defined dataType: as 'json' and the output is json_encode'd by PHP. On the JavaScript console I can see that the response text is:

"{"has_error":false,"result":{"page_id":"xxx"}}" 

Tried copy this and validate with online JSON validator tools, the interesting thing is it was valid a few times and it was invalid a few times (without any consistency) Im a bit confused. Tried to use other headers like:

header('Content-Type: text/json'); 
header('Content-Type:javascript/json');
header('Content-Type: application/json');

or with no header, but nothing.

If I edit the JQuery ajax request's dataType to 'text' (despite the output is JSON formatted and and even the header says it is a JSON content), then the success handler runs and I got the response correctly. In this case the same problem comes when I try to $.parseJSON(response).

What went wrong? Is my JSON string really invalid?

Upvotes: 0

Views: 2601

Answers (1)

epascarello
epascarello

Reputation: 207501

Debug your response to see what characters are there that is making it not valid. Set the dataType to text and escape the text that is returned.

dataType: 'text',
success: function(response){
    console.log(escape(response));
},

You will see the characters that are returned, there is probably some weird return character that is cauing the problem.

Upvotes: 2

Related Questions