JSON data response from PHP server is empty

It’s hard for me to understand this. It seems that no matter what I try, PHP always finishes returning an empty array. Here is the code of my main file (index.php):

<script language="javascript" type="text/javascript">

$(document).ready(function(){

  $(".ajaxlink").click(function() {
    callServer();
    return false; //Stop link from redirecting
  });

});

var test = { "testName": "testValue" }
var testJSON = JSON.stringify(test);

function updatePage(data) {
  document.getElementById("testDiv").innerHTML = data;
}

function callServer() {
 $.ajax({
   type: "POST",
   url: "ajax/server.php",
   data: testJSON,
   success: function(data) {
     updatePage(data);
   },
   //Upon error, output message containing a little info on what went wrong
   error: function (XMLHttpRequest, textStatus, errorThrown) {
     alert('An Ajax error occured\ntextStatus = ' + textStatus + '\nerrorThrown = ' + errorThrown + '\nstatus = ' + XMLHttpRequest.status);
   }
 });
}

</script>

<div id="testDiv">Something here</div>

<a href="test1.htm" class="ajaxlink">Link!</a> <br>

This basically launches the callServer () function when you click "Link!" Then it sends the json test data, that is, {"testName": "testValue"} to server.php. Firebug reports that json-data is indeed sent to server.php.

My server.php looks like this:

<?php

print_r($_POST);

?>

This returns the following in testDiv:

Array
(
)

.ajax , , server.php, . (json, jquery) . Apache 2.2 PHP 5.3.1, - ( -). , , "application/x-www-form-urlencoded; charset = UTF-8 ', .

.

+3
3

, . testName=testValue, test data .ajax() stringify.

, stringify, ( , ):

'{ "testName": "testValue" }'

.

'testName=testValue'

test , .ajax() :

function callServer() {
 $.ajax({
   type: "POST",
   url: "ajax/server.php",
   data: test,
   success: function(data) {
     updatePage(data);
   },
   //Upon error, output message containing a little info on what went wrong
   error: function (XMLHttpRequest, textStatus, errorThrown) {
     alert('An Ajax error occured\ntextStatus = ' + textStatus + '\nerrorThrown = ' + errorThrown + '\nstatus = ' + XMLHttpRequest.status);
   }
 });
}
+3

firefox Live Http Headers.
, ,
Php Js.

http

0

, PHP script JSON.

PHP ( ), json_encode json_decode. :

print_r($_POST);

Try:

print json_encode($_POST);

If your version of PHP does not have these functions, you can use a library such as the Zend_Json class in the Zend Framework to encode your PHP variables as JSON before releasing them.

And when he returns, it will be a JSON string. Setting the data type in your jQuery.ajax call should evaluate it to a JS object. If not, you will either have to call Javascript's eval function on it, or (preferably) use JSON.parse (data).

0
source

Source: https://habr.com/ru/post/1734441/


All Articles