Im sending this AJAX request, but in the server the array is empty. Any help? In Firebug I can see the request is being sent.
$.ajax({
type: 'POST',
url: 'presupuesto_guardar.php',
data: { 'data': '1' },
})
//PHP
var_dump($_POST); //this is empty
The request is being sent:
have you write success function to return response if not then please do as below code
$.ajax({
type: 'POST',
url: 'presupuesto_guardar.php',
data: { 'data': '1' },
success : function(response){
console.log(response);
}
})
Please try php://input to get your post data instead of $_POST
php://input will return all the raw data after header
$post = file_get_contents('php://input');
echo json_encode($post);
Related
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>';
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']
I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.
I'm sending some data over with jQuery/Ajax. My code is marked as POST, but PHP is actually seeing it as GET. What gives?
$.ajax({
url: url,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
callback(results);
},
error: function (req, msg, obj) {
console.log('An error occured while executing a request for: ' + url);
console.log('Error: ' + msg);
}
});
I'm able to confirm it's coming in on the PHP side as GET by doing print_r($_GET) and print_r($_POST)
you r not sending any data in post. try add some data and check in server side.
JS
<script>
$.ajax({
url: url,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data : {
'sample' : 'sample_data'
},
success: function (results) {
callback(results);
},
error: function (req, msg, obj) {
console.log('An error occured while executing a request for: ' + url);
console.log('Error: ' + msg);
}
});
</script>
PHP
<?php
$sample = '';
if (isset($_POST['sample'])) {
$sample = $_POST['sample'];
}
echo $sample;
?>
// Output
sample_data
I think through the url you are passing values instaed of get if you want to post try like
$.ajax({
url: url,
type: "POST",
data:{'my_var':'gautam'},
-------------
and in php you can use like
<?php
print_r($_POST); //or you can print_r($_POST['my_var']);
?>
gives you 'gautam'...
Use $_SERVER['REQUEST_METHOD'] to check if its GET or POST
echo $_SERVER['REQUEST_METHOD'];
Use $_REQUEST[] for getting both POST and GET method values
<?php
print_r($_REQUEST);
extract($_REQUEST);
echo "sample : ".$sample;
?>
output:
sample : sample_data
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);