Empty response by JQuery.ajax and object and php - php

I am stuck by creating my first universal code for ajax responses. I simply do not get an output here, neither in php nor in the ajax response. This must have something to be in the post data.
This is my ajax request:
var info = {};
//get id info
info["ses-id"] = $("#theme").attr("scene");
//get template info
info["ses-template"] = $("#theme").attr("template");
$.ajax({
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(info),
type: "POST",
url: "query.php"
}).done(function(data, textStatus, jqXHR) {
alert (data);
//window.location = "?szenen";
console.log("Data sent.");
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log("There was an error." + errorThrown);
});
This is my query.php so far:
<?php
$return = $_POST;
$return["json"] = json_encode($return);
print(json_encode($return));
The output is an object where only the json entry is filled with [].
The stringified variable looks good, it's a string like this:
{"ses-id":"1","ses-template":"2"}
Thanks for any advice!

Your problem is you are sending a json encoded string as the POST body, and then using $_POST to access it. $_POST is an array of key/value POST data. Since your data doesn't have a key, you can't access it from the $_POST array. It's just a value (a string value at that).
If you change your PHP script to be:
<?php
echo file_get_contents("php://input");
?>
It will output the JSON you passed in. Note that there is no need to do a json_encode() because the value is a string, not an array. The json you passed it was never decoded.
Alternatively, if your javascript was:
$.ajax({
data: { "data": JSON.stringify(info) },
type: "POST",
url: "query.php"
})
then your post body would be:
data={"ses-id":"1","ses-template":"2"}
you could then do
<?php
echo $_POST["data"];
?>
Again noting the data you sent it was never decoded, so it's still just a string. PHP does not json_decode for you.

The dataType and contentType both must be deactivated, then I got responses.
$.ajax({
//dataType: "json",
//contentType: "application/json; charset=UTF-8",
data: JSON.stringify(info),
type: "POST",
url: "query.php"
Varying the info object results in varies of the php var but that wasn't my problem.
BIG thanks to everyone especially CJ_Wurtz who pushed me the right way.

It works when you drop contentType and JSON.stringify:
var info = {};
//get id info
info["ses-id"] = $("#theme").attr("scene");
//get template info
info["ses-template"] = $("#theme").attr("template");
$.ajax({
dataType: "json",
data: info,
type: "POST",
url: "query.php"
}).done(function(data, textStatus, jqXHR) {
console.log(data);
//window.location = "?szenen";
console.log("Data sent.");
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log("There was an error." + errorThrown);
});

Related

How to properly retrieve a JSON string with PHP?

I am trying to send a JSON to my PHP script and for some reason is returning null in the alert message.
I've searched throughout Stack Overflow and other forums and used other people's examples but somehow I keep getting it wrong. I checked in Firebug and the request is being sent. I am very new to handling JSON queries.
Could anyone point at what I am doing wrong so that I can learn for the next time?
My JQuery Code:
var name = $('#formName').val();
var regno = $('#formRegNo').val();
var charityinfo = $('#formCharityInfo').val();
var searchimprove = $('#formSearchImprove').val();
var finantialaid = $('#formFinantialAid').val();
var contactname = $('#formContactName').val();
var contactphonenumber = $('#formContactPhoneNumber').val();
var contactfaxnumber = $('#formContactFaxNumber').val();
var contactemail = $('#formContactEmail').val();
var website = $('#formWebsite').val();
var address = $('#formAddress').val();
var postcode = $('#postCode').val();
var arrayData = {"name":name,"regno":regno,"charityinfo":charityinfo,"searchimprove":searchimprove,"finantialaid":finantialaid,"contactname":contactname,"contactphonenumber":contactphonenumber,"contactfaxnumber":contactfaxnumber,"contactemail":contactemail,"website":website,"address":address,"postcode":postcode};
console.log(name);
$.ajax({
url: "test.php",
type: "POST",
dataType: "json",
contentType: "json",
async: false,
data: arrayData,
success : function(response) {
alert(response);
},
error: function(){
alert("error");
}
}); //End AJAX
My PHP Code:
<?php
$return = $_POST;
echo json_decode($return);
?>
first, collect your form data in 1 step, serialize it as json:
var arrayData = $('#my_form_id').serialize();
If you post your data, you should post the appropriate post variable name with it. Add some more decriptive error handling:
$.ajax({
url: "/test.php",
type: "POST",
data: 'mydata = ' + arrayData,
success : function(response) {
alert(response);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
And then on the php side pick it up:
$mydata = $_POST['mydata'];
$arrayData = json_decode($mydata);
var_dump($arrayData);
You haven't encoded the data you are sending as JSON. You are passing an object to jQuery and allowing it to encode it (as application/x-www-form-urlencoded). You need to encode your data as JSON and pass a string to data:.
json is not a content-type, application/json is.
$_POST is populated from application/x-www-form-urlencoded or multipart/form-data, it doesn't contain the raw post request. You need to use php://input to get that.
First of all you don't need to create json yourself
use JSON.stringify() function function to create JSON
or you can also use the jquery serialize() function
var arrayData=$("FORMID").serialize();
$.ajax({
url: "test.php",
type: "POST",
dataType: "json",
contentType: "json",
async: false,
data: arrayData,
.....
and decode this json serverside using json_decode() function

Submitting JSON data via JQuery ajax.post to PHP

Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I've tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright...
And yea usual string were echoed correctly :-)
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
Quoting from PHP Manual
php://input is a read-only stream that allows you to read raw data from the request body.
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
UPDATE:
When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.
If you must get that using $_POSTyou would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.
To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property.
The following should work as you expected:
this.getAbsence = function() {
var strJSONData = JSON.stringify(this);
alert(strJSONData);
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'ajax/selectSingle.php',
data: 'm=getAbsence&Absence=' + strJSONData,
success: function(data) {
alert(data);
}
});
}
try this
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(vThis),
success : function(data){
alert(data);
}
});
}
EDIT
I think we can also do this!
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ajax/selectSingle.php?m=getAbsence",
data: vThis,
success : function(data){
alert(data);
}
});
}
and in PHP
print_r($_POST);
On PHP side try this:
$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);

How to parse json data received from a jQuery ajax call in php

I'm calling a php script (getNum.php) via ajax after creating an object and using jquery.json to turn
it to json. Now i want to handle the object on the php side.
print_r($_POST['data']) doesn't work nor anything else i've tried.
This is my code:
// create object
var bing= new Object();
bing.id = 99;
bing.nameList = getBingList();
//create pdf
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "getNum.php",
dataType: "html",
data: $.toJSON(bing),
success: function(data){
alert(data);
window.location = "generateBing.php?num="+data
}
});
If you're using print_r($_POST['data']) to show the content, you'll need to send it as "data" as well.
$.ajax({
type: "POST",
url: "getNum.php",
data: {data: $.toJSON(bing)},
success: function(data){
alert(data);
window.location = "generateBing.php?num="+data
}
});
Otherwise you have to do print_r($_POST)
Since you are posting a JSON object directly, there is no argument name for $_POST. You'll need to read the raw contents of the POST request. Try this:
$data = json_decode(file_get_contents('php://input'));
print_r($data);

How to receive and decode JSON strings in PHP?

I had passed the json string through ajax in jquery like this. My JSON file has check boxes and list values.
var jsonstr = JSON.stringify(result);
here 'jsonstr' is the selected form elements.
function runAjax(jsonstr)
{
type:"POST",
url: "ajax.php",
data: 'json=' +jsonstr,
dataType: 'json',
headers: {
'Content-Type': 'application/json',
success: function(){
alert('Test results submitted!');
},
};
return false;
In php I am trying to recieve the JSON stringlike this, but it was giving the output like "null".
$data= $_POST['json'];
//decode Json string to PHP object
$phpobj = json_decode($data,true);
print_r($data);
$phpobj = json_encode($data,true);
Is there anything wrong I am doing and and what should be in decoding part? Can anyone help?
If you want to send it as json string, please give like this
data: {json:jsonstr}
so it should be
$.ajax({
type : 'POST',
url : 'sample2.php',
data: {json:jsonstr},
success : function(data){
alert(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
It should work for you.
Actually there is no need to convert the object to json. You can directly give it in $.ajax .
var data = {name:"Jack", age:12, place:"CA", marks:70};
$.ajax({
type : 'POST',
url : 'post.php',
data: data,
success : function(data){
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
}
});
and in php you can read like
$_POST['name']
$_POST['age']
$_POST['place']
$_POST['marks']
Please check the value of $_POST['json']. It should contain something like {"a":"aaa", "b":"bbbb"}.
Check section "Example #3 common mistakes using json_decode()" here http://php.net/manual/en/function.json-decode.php
You can try the following:
In Javascript change
var jsonstr = JSON.stringify(result);
and
data: 'json=' +jsonstr,
to a simple
data: JSON.stringify({json: result}),
.
In PHP read data instead of this way
$data= $_POST['json'];
in this one
$data=json_decode(stripslashes(file_get_contents('php://input')));
Once done that, access your data in this way:
$data->{'variable-name'}
You're very lucky, I understand this question
var jsonObject = eval("(" + jsonFormat + ")");

jQuery AJAX call (POST to PHP) issues

I need to use the $.ajax() call within jQuery to post a little bit of JSON to my PHP script.
I have tried everything but nothing works as I would like it to. I simply try to echo a var_dump of the $_POST/$_GET arrays but it comes back empty.
var myJSONObject = {"bindings": [{"conversation": _conid} ]};
var obj = $.toJSON(myJSONObject);
$.ajax({
type: "POST",
url: "./code/ajax/fetch_messages.php",
data: obj,
async:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
},
beforeSend: function (XMLHttpRequest)
{
},
complete: function (XMLHttpRequest, textStatus)
{
}});
I can see that the post is made by looking in the headers:
{"bindings":[{"conversation":"38x001c61450ad4d5abd47c37408e8236eb5427f54e2930000306882646e4016c5f8ecf8e00a18a26ab3b6d07f6727bd187625daaedf951f93072d54d59e300e100"}]}
PHP:
echo var_dump($_POST);
Everything works great when using the $.post() call but I always run in to problems when I try to switch to $.ajax. I need to use it to be able to retreive the response UTF-8 encoded.
The code pasted in this post is just one of many snippets I've tried, even examples from tutorials on the web does not work.
Could someone please give me a snippet that you know do work so I can try that? Sending JSON through POST.
I think you must give your json string a key, so you can get it on the other side (PHP):
data: {"myjson": obj},
Then on PHP it will be in $_POST['myjson']
below is a slice of my routine and it works fine :
var data = 'post_type=' + post_type.val() + '&page_id=' +
page_id.val() + '&home_page='
+ home_page.attr('checked') + '&archive_page=' +
archive_page.attr('checked') + '&search_page=' +
search_page.attr('checked');
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "?service=set_data",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: true,
//success
success: function (html) {
$(".no-items").hide("slow");
$("#list_table").append(html).hide().slideDown('slow');
}
});

Categories