Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
Is it possible that you have a space before the json-content begins? –  OptimusCrime Oct 21 '13 at 12:17
    
@OptimusCrime, yes good thought, although actually it was a BOM character. –  ACs Oct 21 '13 at 12:59

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
Thanks for the advice. The response started with a %uFEFF (BOM) character, and after a short investigation I have found a file which was saved with BOM. –  ACs Oct 21 '13 at 12:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.