I'm sending some data to my sever at localhost
using jquery's $.ajax
.
The data is JSON
object.
as follows:
javascript
var jso={
"data": {
"Game_name": "Road Rash",
"cheat": "xyzzyspoon!",
"effects": [
{
"nitro": true
},
{
"chain": false
}
]
}
};
function sendData(){
var queryString=JSON.stringify(jso);
$.ajax({
type: "POST",
url: "/gamers_cheats.php",
contentType: "application/json; charset=utf-8",
traditional: true,
dataType: 'json',
data: queryString,
success: function(data){
console.log(data);
},
error: function(data,textStatus,jqXHR){
alert("Unknown Error occured :- \n "+textStatus+"\n error");
console.log("Unknown Error occured :- \n "+textStatus+"\n error");
}
});
}
sendData();
and handling data in my php
file as:
gamers_cheats.php:
<?php
var_dump($_POST);
echo"\n Count:- ".count($_POST);
// This is Just a demo file
?>
But the problem is $.ajax
alerts the error:
part with textStatus
as parsererror. Also same is happening even if I didn't use JSON.stringify.
and if The lines:
contentType: "application/json; charset=utf-8",
traditional: true,
dataType: 'json',
were removed then the request is sent to the sever but that isn't a valid request as it adds extra slashes (\
) to every ("
) in JSON
object.
like:
\"data\": {
\"Game_name\": \"Road Rash\",
\"cheat\": \"xyzzyspoon!\",
\"effects\": [
{
\"nitro\": true
},
{
\"chain\": false
}
]
}
So that gives error while processing it on server side. Is there any way to properly send POST
JSON data using jquery ajax and to properly handle it on server?
and one more question, can i add extra $_POST
parameters which are not in JSON
format to my queryString
as data: queryString +"&&navigator="+navigator.userAgent+""
? but that also ain't working (This is not important though, Just curious about it).
FYI I'm running IIS 7 server with php 5.2 and JQuery version 1.7.2 with JSON2.js .
Hope experts here will help me.
$_POST
. – Ja͢ck Oct 12 '14 at 9:35POST
then how come$_POST
is empty? can you tell that. – Vedant Terkar Oct 12 '14 at 9:38json_decode(file_get_contents('php://input'))
– Ja͢ck Oct 12 '14 at 9:39