3

I use this jQuery function to get data through Ajax:

function addContentPrt(cid){
   $.ajax({
    url: "<?=parseLink('addContent.php')?>",
    type: "POST",
    cache: true,
    dataType:'json',
    data: {id: cid},
    success: function(returnedData){
      console.log(returnedData);
    },
    error: function (xhr, tst, err) {
      console.log(err);
    } 
  });
}

and on the receiving end:

<?
  header("Content-Type: application/json", true);

  if(isset($_POST['id'])) {
    $id = $_POST['id'];
  }

  $sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");

  $r = mysql_fetch_array($sql);
  echo $r['title'];
  echo $id;
?>

the echo $id does return to ajax, but not $r['title'], with that it goes null in console. If I add some dummy text like hello world, I get a synthax error SyntaxError: Unexpected token h {stack: (...), message: "Unexpected token h"}

What could be the cause of this and what could I do to fix it?

raccon
  • 33
  • 4

3 Answers3

4
<?
  header("Content-Type: application/json", true);

  if(isset($_POST['id'])) {
    $id = $_POST['id'];
  }

  $sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");

  $r = mysql_fetch_array($sql);
  echo json_encode('id' => $id, 'title' => $r['title']);
?>

and in your ajax success:

success: function(returnedData){
  console.log(JSON.parse(returnedData));
},
Legendary
  • 2,243
  • 16
  • 26
0

In the ajax, you specified the datatype as json which is the format expecting from the server, So in order to get a result, you need to return the json result from the server. Either by using json_encode($r) where $r can be any array.

Sanjay Kumar N S
  • 4,653
  • 4
  • 23
  • 38
  • I did that and it still returns `null` – raccon Apr 07 '15 at 09:05
  • ... or create the array yourself and pass it back: `$results = ['id' => $id, 'title' => $r['title']]; echo json_encode($results);` Oh, and you need to provide the specific header. Check this topic: http://stackoverflow.com/questions/4064444/returning-json-from-a-php-script – mzografski Apr 07 '15 at 09:06
  • Are you sure the $r['title'] or $id is setting in the server side? – Sanjay Kumar N S Apr 07 '15 at 09:10
0

return json_encode($r); then you can read variable $r in sucess

Zied R.
  • 4,964
  • 2
  • 36
  • 67
kailash sharma
  • 356
  • 1
  • 12