Why is my JQuery variable not sending to php? - javascript

I have a variable which contains data, i'm then using a ajax function to send this variable data to this php file. I'm slightly unsure I can store this variable into php and echo it out. This is the code that I currently have...
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: data,
success: function(data) {
alert ( data );
}
});
This is my php code
$noteone = $_POST['data'];
echo $noteone;
Any help would greatly be appreciated

data of your ajax call should be like below. Hope it will solve your problem.
data: { "data": data }

You also need to set the data type:
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: { "data": data },
dataType: "json", // <---- THIS ONE
success: function(data) {
alert ( data );
}
});

Try this :
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: JSON.stringify(data),
contentType: "application/json",
success: function(data) {
alert ( data );
}
});

PHP requires data to be submitted in key=value format when building $_POST/$_GET. You didn't do that. You only submitted value, so PHP has no key to populate $_POST with. You need to have:
data: { "whatever_you_want": data }
which becomes
$_POST['whatever_you_want']

Related

How to intercept POST data with Javascript

I am using this javascript function to send data to my php script (via POST) I am then using this information to retrieve data from my database and I would like to reuse the information retrieved in my JavaScript code.
Here is my code :
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function() {
// HERE I would like to inctercept the data that my php script put in myFunctions.php produces and use it to generate content;
}
});
});
So basically, when clicking on the button #validerChoixDeCours, my code sends some data to myFunctions.php which generates a response stored in a php variable and I want to use that response in my JS code.
Thank you in advance for your help :)
Its actually quite easy!
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(e) {
e contains the response from the php script
}
});
});
The first parameter of success contains the response from the request. so, in this case, the 'e' variable contains the output which you can use.
Add data variable
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(data) {
alert(data);
}
});
});
make sure your server side code look like this
<?php
$output = "Any String or Array";
echo json_encode($output);
?>

javascript variable to php NULL

I use simple AJAX request to pass JavaScript variable to PHP via AJAX.
This my AJAX request:
var image_url = "example";
$.ajax({
type: "post",
//url: 'index.php', // the same file
data: { image_url : image_url },
success: function(data) {
alert here works!
}
In the same file, on the first line i have
<?php var_dump($_POST['image_url']); ?>
On my page I see always NULL
Can someone help me?
Note that all the server-side PHP code on has already run once you're interacting with the page client-side, so you won't be able to access the $_POST['image_url'] using PHP as you appear to be attempting.
That being said, any resultant data from your AJAX request will be in the data variable of your success function.
$.ajax({
type: "post",
//url: 'index.php', // the same file
data: { image_url : image_url },
success: function(data)
{
console.log(data); // this is where your data is
}
}

Load and then append on AJAX Success

I'm using AJAX to send inputted data to the database which I've managed to achieve. Where I'm struggling is on the success parameter. I'm trying to load and then append a PHP file once the initial AJAX call is successfully completed.
var data = $("#form_write_post").serializeArray()
$.ajax({
type: "POST",
url: $("#form_write_post").attr("action"),
data: data,
async: false,
success: $.get("test.php", function(data) {
$('ul.timeline').append(data);
});
});
I managed to append JavaScript data but I need to be able to get other data from the database.
Thanks
remove $.get(){} in success
$.ajax({
type: "POST",
url: 'test.php', //if ur action is test.php
data: data,
async: false,
success: function(data) {
$('ul.timeline').append(data);
});
});

How to pass data using jQuery/ Ajax to a URL

How to pass the fetched data using $.get() from a URL to a particular URL with query_string that can be retrieved using $_GET() in PHP. I'm using following but not working. I want to pass the fetched data into following parameter http://example.com/data?data=FETECHED_DATA
<?php
$ip_address=$_SERVER['REMOTE_ADDR'];
echo '<script>
$.get( "http://ipinfo.io/'.$ip_address.'/org", function( data ) {
$.ajax({
type: "GET",
url: "http://example.com/data",
data: data,
success: success,
dataType: dataType
});
});
</script>';?>
Well, don't recommended PHP to fetch and send data
I believe this will do what you want
<?php
$ip_address=$_SERVER['REMOTE_ADDR'];
echo '<script>
$.get("http://ipinfo.io/'.$ip_address.'/org", function(data) {
$.ajax({
type: "GET",
url: "http://example.com/data",
data: {data : data},
success: success,
dataType: dataType
});
});
</script>';?>
the only change is data: data changed to data: {data: data}
that's a lot of data :p
see this cut down mock up, http://jsfiddle.net/cm8o5dk8/ if you have a decent browser that can show you the network "usage" you'll see that the mockup fails trying to GET http://example.com/data?data=AS15169+Google+Inc.%0A - the %0A comes back from ipinfo.io
Thanks it worked
$.get("http://ipinfo.io/8.8.8.8/org", function(data) {
$.ajax({
type: "GET",
url: "http://example.com/data",
data: {data : data},
success: function() {},
dataType: 'json'
});
});

JS array send to php is returning as empty [duplicate]

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

Categories

Resources