Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't read json encoded data

I'm working on a super simple chat php and jQuery ajax based, but I'm having a problem in displaying a json encoded string through the ajax callback function.

Here's the ajax request:

$.ajax({
  url: "/pages/core.chat.php",
  type: "POST",
  dataType: "json",
  contentType: "application/json",
  data: {'action' : 'loadChat'},

  success: function(resp) {
    $("#chatBody").html(resp.refreshChat);
 }

});

and this is from the .php file

if ($_POST['action'] == 'loadChat') {   
    $resp = array("refreshChat"=>$chat);
    echo json_encode($resp);
}

where $chat contains the message text. All I get is a blank page. Also, if I send the ajax request without the dataType and contentType parameters and run the callback without .refreshChat, it prints the json encoded string as it's meant to be {"refreshChat":"chatmessage"}, so maybe the problem lies in the way I'm passing those parameters? Just guessing. I'm quite new to jQuery ajax and I've checked, double checked and triple checked but I don't know what I'm doing wrong. Thanks to anyone that can make the magic.

like image 634
mzG Avatar asked Apr 26 '26 15:04

mzG


1 Answers

When using contentType: 'application/json' you will not be able to rely on $_POST being populated. $_POST is only populated for form-encoded content types.

 $.ajax({
  url: "/pages/core.chat.php",
  type: "POST",
  dataType: "json",
  contentType:"application/x-www-form-urlencoded",
  data: {'action' : 'loadChat'},

  success: function(resp) {
    $("#chatBody").html(resp.refreshChat);
 }

});

If you want to send contentType:application/json you should actually send JSON, which you are not doing.

like image 64
FelixHo Avatar answered Apr 29 '26 03:04

FelixHo



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!