Jquery POST request to another PHP file not working - php

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

Related

Why my php backend don't have data of json post?

I have got array of json:
[Object { path="/usr/share/htvcenter/storage/Windows", imgid="14698227485587"}, Object { path="/usr/share/htvcenter/storage/WindowsServer", imgid="14701636866762"}]
And I send this array with ajax:
$.ajax({
type: 'POST',
url: urlstring,
contentType: "application/json",
data: JSON.stringify(parameters),
success: function(data){
$('.lead').hide();
blackalert('Removed successfully!');
}
});
I see this in firebug for post send:
But server answer is with empty $_POST:
Server's code is:
if (isset($_GET['treeaction']) && $_GET['treeaction'] == 'remove') {
echo 'here';
var_dump($_POST); die();
}
What I am doing wrong?
When you send a POST request you don't need to set the content type to application/json. By doing so this is no longer a regular POST request (with form values), but a payload request.
To get the data from a payload request on your server you can use:
$content = file_get_contents("php://input");
var_dump(json_decode($content)); // In case the content is a json string.
If you want to send a regular request, you can use:
$.ajax({
type: 'POST',
....
data: {'data' : parameters},
success: function(data){
alert(data);
}
});
Without the contentType and without the JSON.stringify.
This way you can get the data with $_POST['data']

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

jQuery Ajax posting not working

My jQuery ajax posting is not working. Here is the javascript
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: postData,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
I am saving the data to be posted inside a hidden div like
<div class='WrapperDiv hidden'>{"post_id":392,"url":"http:\/\/www.wordpress-site\/post\/post-title\/","title":"SEO Friendly title"}</div>
All I am getting in return from the post.php page is an empty array. Here is my code for post.php
<?php
if(isset($_POST)){
print_r($_POST);
} else {
echo "0";
}
?>
Any Idea whats wrong?
EDIT : Its working after I removed
contentType: "application/json",
dataType: 'json'
What about something like this:
var postData = "data=" + encodeURCIComponent($buttonWrapper.html());
Than in PHP:
echo $_POST["data"];
Than parse it or something....
Couple of things to try,
Try to pass the data directly in to the data object first. If it
works then you can debug and see why it's not ready your hidden div.
instead of $buttonWrapper.html try $buttonWrapper.text();
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.**text**();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: **{'id':1}**,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Inside your jQuery ajax call, your data is not set to $_POST variable names. Hence why nothing is showing
Try changing your function to this:
function SocialButtons() {
var buttonWrapper = jQuery('.WrapperDiv');
if (buttonWrapper.length){
var postData = buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: {postData: postData},
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Then you should have a $_POST['postData'] variable on your print_r or var_dump of $_POST.
Its working after I removed
contentType: "application/json",
dataType: 'json'

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

Categories