Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data not returning from ajax POST

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?

like image 601
raccon Avatar asked Apr 24 '26 05:04

raccon


1 Answers

<?
  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));
},
like image 110
Legendary Avatar answered Apr 25 '26 17:04

Legendary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!