0

I am sending a simple array from my PHP file,

//example.php
if(0){
    return json_encode(['status'=>false, 'message'=>'Please enter a username']);
}

and in my ajax.js I have everything working, including the XHR object, and event handlers. All is find, except this line.

 // ...
 var x = JSON.parse(xmlhttp.responseText);
 console.log(x); 
// ...

But, I am getting the following error.

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

I don't understand this. All the code is correct. Before using JSON, I used to pass from values from PHP using echo 'ok' and just do if(xmlhttp.responseText) == 'ok and it worked fine, but not with json

10
  • You'll have to look at whatever response your PHP actually returned (leading/trailing garbage/HTML). And if(0){ probably doesn't help. Commented Feb 19, 2015 at 23:46
  • Nope, the PHP file is clean. I checked. There is nothing being sent except the array. Commented Feb 19, 2015 at 23:47
  • 1
    Can you post the full response of the PHP file? Get it from your browsers console. Commented Feb 19, 2015 at 23:48
  • @Scopey the error is the full response, though there are two empty string being displayed before and after the error. both double-quoted empty strings. Commented Feb 19, 2015 at 23:50
  • Try running trim() or filter out empty elements in your array. Commented Feb 19, 2015 at 23:50

1 Answer 1

1

Two problems:

  • you use return which does not print anything to the output wheras echo actually prints text. Try using:

  • if(0) will always fail, so you will never print anything. You should use if(1) as trivial test. It is possible that you're PHP code can fail, but in that case you better also return an JSON formatted error message.

Something like:

if(test) { //test means you can do the action
    //do action
    echo json_encode(['return' => 'ok','result' => 'foobar']);
} else {
    echo json_encode(['return' => 'error']);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, it turns out I should have used echo. the (0) part was written here by mistake. But, one problem I have is that, echo outputs data to the browser before actually javascript can for example redirect the page. Any solutions to this problem?
What output? The fetched page? It's rather hard to debug this without any page source...
I mean, for example, in the code you have given. if there is no error, I can see {return:ok, result:foobar} in the page, because the javascript can decode the json format and do some action, like page redirect. So, in the registration page, I have, people will see the serialized data no matter what, because echo just outputs it to the browser.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.