This is my Ajax call which I have copy pasted from a script
$.ajax({
type: "POST",
url: "createpdf.php?v=635473328964700000",
data: optionsJSON,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: calls.beforeSend,
success: calls.success,
error: calls.error,
complete: calls.complete
});
When I inspect my console in firefox
In params tab it says
v 635473328964700000
In POST tab it says
{'path':'services/imgProcess.php?c=ixs&t=rt7&ap=0&bp=0&cp=0&a1=01&a2=01&a3=01& a4=01&a5=01&a6=01&a7=01&a8=01&a9=01&a10=01&a11=01&a12=01&a13=01&a14=01&a15=01&a16=01&a17=01&a18=01&a19=01&a20=01&b1=01&b2=01&b3=01&b4=01&b5=01&b6=01&b7=01&b8=01&b9=01&b10=01&b11=01&b12=01&b13=01&b14=01&b15=01&b16=01&b17=01&b18=01&b19=01&b20=01&c1=none&c2=none&c3=none&c4=none&c5=none&c6=none&c7=none&c8=none&c9=none&c10=none&c11=none&c12=none&c13=none&c14=none&c15=none&c16=none&c17=none&c18=none&c19=none&c20=none&l=1&acc-kitr=0&acc-kitm=0&acc-additionalkit=additionalkit&acc-plasticprotection=0&acc-fingerprotection=0&acc-knuckleprotection=0&acc-ballsthumb=0&width=720&height=480&cache=1411735356642','accessories':'{
"sliders": "0",
"kitr": "0",
"kitm": "0",
"additionalkit": "additionalkit",
"plasticprotection": "0",
"fingerprotection": "0",
"knuckleprotection": "0",
"ballsthumb": "0"
}'}
In Response it says Array()
I have this code in my createPDF.php file
print_r($_POST);
How I can retrieve posted data on server side. Please help me this is very confusing..
try this
$.ajax({
type: "POST",
url: "createpdf.php?v=635473328964700000",
data: optionsJSON,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(data){
console.log(data);
//json parse
var obj = JSON.parse(data);
console.log(obj);
}
});
Now you can access the json data by using obj object e.g. var name = obj.name;
Currently you are sending data in json format, so php cannot parse the data into the $_POST array.
Either change your ajax to send post data:
data: {options: optionsJSON},
//contentType: "application/json; charset=utf-8",
or change your php to access the raw post stream
print_r(file_get_contents('php://input'));
Related
I have the following code:
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: JSON.stringify(arr),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
The result is null. In the PHP side I have:
echo json_encode($_POST);
and
print_r($_POST);
But both are giving empty results (checked Firebug also).
You can also set the dataType in Ajax to specify the content type as follows.
var city='city name';
var age=10;
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data:"City="+city+"&Age="+age,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
and in cities/index.php you can get this data by follows
if($_POST){
$city=$_POST['City'];
$age=$_POST['Age'];
// and do with $city and $age what you want.
//for return anything thing to `json` use follows we pass $age back to ajax
echo json_encode($age);
}
I guess you don't need to stringyfy the data because data should be PlainObject or String but in your case you can simply write like below
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: arr,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
as documented in jquery official site https://api.jquery.com/jQuery.ajax/
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
The data option passed to $.ajax() must be either a simple object, that jQuery will transform into a string of the formatkey1=value1&key2=value2.. OR it should be a string of the form key1=value1&key2=value2...
In your case, it can be solved by passing the object itself and letting jQuery do the query string formatting:
$.ajax({
...
data: arr,
...
});
try this
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: arr,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
We want to post a json object to PHP, this is what we currently have:
var sitePersonel = {};
var userData = [];
sitePersonel.userData = userData;
var userData = {
"userId": username,
"name": name,
"artists": artistNames
};
sitePersonel.userData.push(userData);
console.log(sitePersonel);
var jsonpArray = JSON.stringify(sitePersonel);
function phpCallback() {
}
$.ajax({
type: "POST",
dataType: "jsonp",
url: "http://student.cmd.hro.nl/0879644/spotify/data.php",
data: { myData: jsonpArray },
success: function (data) {
alert('Items added');
},
jsonpCallback: phpCallback(),
error: function (e) {
console.log(e.message);
}
We are getting an error, on loading this jQuery. We have tried debugging, but onfortunately, we aren't getting far. Our console gives the following error:
Resource interpreted as Script but transferred with MIME type text/html
We do land into the phpCallback(); but the console is giving us errors and PHP isn't working either.
We want to send the JSON object to PHP to save into a database. We are working on a Spotify App.
Try changing content type to text/javascript
JSONP request: "Resource interpreted as Script but transferred with MIME type text/html"
Hope this solves your problem.
plain example, modify to your own case (i.e. dataType from json to jsonp)
jQuery.ajax({
url: url,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: callback
});
Add content-type in your ajax
contentType: "application/json",
By default it is 'application/x-www-form-urlencoded; charset=UTF-8'
Here is a partial example of what I am trying to achieve.
I am trying to retrieve a value from ajax but the javascript result.success variable is undefined. I have the following:
PHP:
$result = array ("success" => null, "html" => "");
$result['success'] = true;
$result['html'] = "test";
echo json_encode($result);
Javascript/jQuery:
var ID = 1
$.ajax({
type: 'POST',
url: '/ajax/load.php',
contentType: "application/json; charset=utf-8",
datatype: 'json',
data: {ID: ID},
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function(result) {
if (result.success) {
// do something
}
});
The response I am getting from ajax (retrieved from chrome dev tools) is {"success":true,"html":"Test"}
This looks fine to me however in the JavaScript result.success is undefined. I believe this will be simple I just can't see where the issue lies..
Your error is here:
datatype: 'json',
Javascript is case sensitive and the property is dataType:
dataType: 'json',
Because of that, jQuery is not being told to automatically parse the JSON, so the result is just treated as html or plain text.
You also need to remove the content-type header because that specifies the content type for the request not response. You are sending form/url encoded in the request, not JSON.
$.ajax({
type: 'POST',
url: '/ajax/load.php',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: {ID: ID},
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function(result) {
if (result.success) {
// do something
}
} // Maybe your forgot this
});
in other words - Basic Debugging
in your PHP page put this on top of the page (you are accepting only json response but probably your response headers content type is text/html
header('Content-type: application/json');
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);
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);