0

this php:

$token = NoCSRF::generate( 'csrf_token' );
$status = "succeed";
$message = "Update done!";
$return = array($status,$message,$token);
//header('Content-type: application/json');
echo json_encode($return);

returns

"↵["succeed","Update done!","MTQ0NDcxNzM3Nm9nUTRCVzRKOXc5RXFocUZodXh5eXo4Tm5waTlzZ05a"]"

to the browser which js can't handle.

If I uncomment the header line in the php it returns

["succeed", "Update done!", "MTQ0NDcxNzIyNnAwY01LMVZHdXV6TE1ZT3FZZHhpd2JZcnM0RTl0Rm81"]

and works OK

Any idea what's going on here? I can't just leave the header line uncommented because this solution doesn't work on the live hosted site although it does my dev site as above...

AndyK
  • 21
  • 2

2 Answers2

0

It has to do with the fact that by default, the json is sent through text/html. When using Content-type: application/json, the browser is accepting JSON encoded data that can be manipulated in javascript.

More info is available in this question.

Community
  • 1
  • 1
  • @RamRaider I'm only seeing this issue where I'm handling the AJAX send and return using jquery. So when I'm doing this I get the problem: `$.ajax({ type: "POST", url: url, data: $("#find").serialize(), // serializes the form's elements. success: function(response) {` but when I'm doing this it's fine: `XHR.addEventListener("load", function(event) { if (XHR.readyState==4 && XHR.status==200) { var response = JSON.parse(XHR.responseText);` – AndyK Oct 13 '15 at 19:51
  • in my live implementation I have `Content-type: application/json` in place but I still see the problem – AndyK Oct 13 '15 at 19:57
0

@Josh's beforeSend code in this thread has sorted this for me:

var jsonMimeType = "application/json;charset=UTF-8";
$.ajax({
 type: "GET",
 url: myURL,
 beforeSend: function(x) {
  if(x && x.overrideMimeType) {
   x.overrideMimeType(jsonMimeType);
  }
 },
 dataType: "json",
 success: function(data){
  // do stuff...
 }
});
Community
  • 1
  • 1
AndyK
  • 21
  • 2