Submitting JSON data via JQuery ajax.post to PHP - 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);

Related

Jquery POST request to another PHP file not working

I am trying to make a post request to send some data from one php file to another. I'm using Jquery and my code looks as follows
My post file:
$(function (){
$(".commit").click(function(){
const sha_id = $(this).data("sha");
$.ajax({
url : 'commitInfo.php',
type : 'POST',
data : sha_id,
contentType: "application/json; charset=utf-8",
success: function(response){
console.log(sha_id);
window.location.replace("commitInfo");
}
});
});
});
My receiving file:
var_dump($_POST);
The $_POST returns an empty array. And have also tried placing my data inside of an object. Doesn't work either. Anyone know what is wrong?
Check your variable which contain data before sending the ajax request to the server by console it to the browser.
Ajax request carry data into key value pair or json format you need to send json object to the server to get the access to the data
$.ajax({
url : 'whatever-folder/whatever-url.php',
type : 'POST',
data : { anykey: anything },
contentType: "application/json; charset=utf-8",
success: function(response){
console.log(response);
}
});
and you will get the post in the server.
Have your tried using the FormData see
$(function (){
$(".commit").click(function(){
const sha_id = $(this).data("sha");
var data = new FormData();
data.append('id',sha_id );
$.ajax({
url : 'commitInfo.php',
type : 'POST',
data : data,
processData: false,
contentType: false,
success: function(response){
console.log(sha_id);
window.location.replace("commitInfo");
}
});
});
});
(1.). post file:
$(function (){
$(".commit").click(function(){
const sha_id = $(this).data("sha");
$.ajax({
url : 'commitInfo.php',
type : 'POST',
dataType: 'json',
data : sha_id,
contentType: "application/json; charset=utf-8",
success: function(response){
console.log(sha_id);
window.location.replace("commitInfo");
}
});
});
});
(2.). Json data does not receive in post.
$json = file_get_contents('php://input');
$post = json_decode($json, TRUE);
echo '<pre>';
var_dump($post);
echo '</pre>';

Jquery ajax response error

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');

PHP isn't recognizing data posted by ajax

I'm sending an ajax call to my PHP script as follows:
function load(){
var request = {};
request['action'] = 'load';
request['file'] = 'lorem_ipsum.txt';
$.ajax({
type: 'POST',
url: cgi_file,
data: JSON.stringify(request),
processData: false,
dataType: 'html',
contentType: 'application/html',
success:function(response){
console.log("received " + response);
}
});
}
and my PHP script is as follows:
$content_dir = '/static/content/';
$action = $_POST['action'];
switch ($action){
case 'load':
$file = $_POST['filename'];
echo file_get_contents($content_dir . $file);
exit();
}
The PHP is responding with the following failure:
Notice: Undefined index: action in /var/www/river/api.php on line 5
What's the issue here?
Try ditch processData: false and contentType: 'application/html' and it should work
$.ajax({
type: 'POST',
url: cgi_file,
data: request,
dataType: 'html',
success:function(response){
console.log("received " + response);
}
});
Just leave data as it is:
data: request,
You don't need to stringify it.
Also, your file parameter allows an attacker to read arbitrary files from your filesystem. Sanitize it.
A few things wrong here, firstly the contentType property is for the data you are sending to the server, secondly dataType should be set to text as that is what you are recieveing from the server. If you want to receive the data in the $_POST array your javascript should look like this,
$.ajax({
type: 'POST',
url: cgi_file,
data: {
action: "load",
file: "lorem_ipsum.txt";
},
dataType: 'text',
success:function(response){
console.log("received " + response);
}
});
Jquery will send your data as a standard post to your server side code.

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);

php json_encode not returning proper json encoded string

I am using a jquery ajax call which accepts json response :
var posturl = '/admin/getparamdetails/';
var data = "adnetworkId="+adnetworkId;
$.ajax({
type: "POST",
url: posturl,
data : data,
datatype: "json",
success: function(msg){
//$("#displayPramForm").html(msg);
//alert('hello'+msg.length+' '+msg.hello.length);
console.log(msg);
if(msg!='')
{
alert(msg.hello);
}
},
failure: function(msg){}
});
in my php backend function , I am using json_encode on a simple array as shown:
$json_encoded_string = json_encode(array("hello"=>'abc'));
echo $json_encoded_string;
die;
but alert(msg.hello) returns undefined for me. What is going wrong here ?
Also , in my console.log I am able to get the output as :
{"hello":"abc"}
Use parseJSON on the return data:
if (msg) {
msg = $.parseJSON(msg);
alert(msg.hello);
}
you have to send the data as Content-Type "application/json", otherwise it won't work.
Just add the following in your PHP File:
header('Content-type: application/json');

Categories