0

PHP

<?php

header("Content-type: application/json") ;
echo json_encode(array("reply" => "SOME_TEXT")) ;

?>

it echos this ->

{"reply":"SOME_TEXT"}

Javascript

<script>
$.get("script.php" , function(data) {
    var reply = JSON.parse(data) ;
}) ;
</script>

JS throws unexpected token in JSON. But it will working fine if I replace the header in PHP code with header("Content-type: text/javascript") or "text/plain".

1 Answers1

5

jQuery parses the data automatically if the header is set to application/json, so you are trying to parse an object. You can use it without JSON.parse with the header set to application/json:

$.get("script.php" , function(data) {
    console.log(data.reply);
}) ;

As @charlietft commented,

using $.getJSON() instead of $.get() will also assure it is parsed

baao
  • 71,625
  • 17
  • 143
  • 203