3

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.

mzG
  • 33
  • 3

5 Answers5

1

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.

FelixHo
  • 1,254
  • 14
  • 26
0

using the header("Content-Type: application/json", true); in your PHP code to specify that the PHP is returning json could help

reayn3
  • 363
  • 5
  • 16
  • it is specified in ajax request `dataType: "json",` – guradio Nov 27 '15 at 02:41
  • indeed @guradio, the javascript code specifies that it expects to get a json response back but the web server may respond with a different MIME type. Specifically placing the header in the PHP code may help to debug the issue. – reayn3 Nov 27 '15 at 02:45
  • This wont resolve the issue, please test your code before sending an answer – Tomas Ramirez Sarduy Nov 27 '15 at 04:05
0

I have met one question which is similar with yours.here's my answer.

PHP have there ways to get POST data.

1.$_POST,which is usually for form data

2.$HTTP_RAW_POST_DATA,if you can't get data from $_POST,try this one.

3.$raw_post_data =file_get_contents('php://input', 'r'); basically the same as $HTTP_RAW_POST_DATA,but more effective.

rain
  • 243
  • 1
  • 8
0

There is no problem with your parameters dataType and data, the problem is with the contentType: "application/json", if you are using Chrome Dev Tools or something similar to check the server response, you should see something like this:

<br />
<b>Notice</b>:  Undefined index: action in <b>core.chat.php</b> on line <b>x</b><br />

That's because core.chat.php is checking for a POST parameter and you are sending JSON.

The PHP superglobal $_POST, only is supposed to wrap data that is either

  • application/x-www-form-urlencoded (standard content type for simple form-posts) or
  • multipart/form-data-encoded (mostly used for file uploads)

Solution 1

Send json and get the json data request via php://input changing your PHP code to receive JSON data instead of $_POST:

in the ajax call change the data parameter:

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

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

});

Change your PHP file to get json data and process it:

$data = json_decode(file_get_contents('php://input'), true);
if($data['action'] == 'loadChat')
   //do something

Solution 2

Remove contentType parameter from the Ajax call, by default is 'application/x-www-form-urlencoded; charset=UTF-8', and is what you would be expecting from the beginning.

Tomas Ramirez Sarduy
  • 17,294
  • 8
  • 69
  • 85
0

Solution 1

You can and should set the Content-Type header:

<?php
header('Content-Type: application/json');

# Code ...

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

Otherwise, what are returning PHP is text only. More info: Returning JSON from a PHP Script

The Content-type header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.

The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json then parse it as JSON.

This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-type to detect what to do with it.

-- Rocket Hazmat - HTTP Content-Type Header and JSON

Solution 2

Or we could fix it with:

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

    success: function(resp) {
        // JSON.parse solution
        resp = JSON.parse();
        $("#chatBody").html(resp.refreshChat);
    }

});

Documentation: JSON.parse

Community
  • 1
  • 1
Chofoteddy
  • 747
  • 9
  • 22