how to use ajax response data in php - php

I am having problem with response data. I want to use response data in my php file. I want to assign them to a php variable.
here is the ajax code in insert.php file.
function change(){
var tp=$('#choose').val();
var country_val=$('#country_filter').val();
//alert(country_val);
//var country_val=$('#country_filter').val();
$.ajax({
type: "POST",
url: "filter.php",
data: { name: tp, country:"test"},
success:function( data ) {
alert(data);
}
});
}
here is php code in filter.php
if($_REQUEST["name"]){
$lvl = $_REQUEST["name"];
//global $lvl;
echo $lvl;
}
Now I want to use the response data to be assigned to a php variable in insert.php file. How may I do that?
Please help.

Send the data to insert.php file using ajax, instead of alerting it.
change success function to
$.ajax({
type: "POST",
url: "filter.php",
data: { name: tp, country:"test"},
success:function(response) {
var res = response;
$.ajax({
type: "POST",
url: "insert.php",
data: { res: res },
success:function(data){
alert(data);
}
});
});
In insert.php,
use this to get the variable.
$var = $_POST['res'];

If insert.php calls filter.php with ajax and then returns a value. you cannot apply that javascript var to a php var in the insert.php. That is because the Php script runs on the server when the page is loaded, and the javascript runs locally on the users computer. To apply anything to a php variable you will have to reload the page.

Related

Ajax post not sending data to PHP file

So I am working on a project in which I have to pass some form data to a database without reloading the page using Ajax. But the $_POST variable in the PHP file is always empty. I do know that I am actually getting the data from the form since I can print and it looks okay in the javascript code:
$(document).ready(function () {
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
type: 'POST',
data: {name: 'tony'},
dataType: 'json',
success: function (response) {
$('#message').html(response);
}
});
//return false;
});
});
And this is the php code:
<?php
//var_dump($_POST);
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
} else {
echo "error";
}
?>
Use this code instead, you won't need to manually define the parameters to be sent because it will be automatically set by FormData():
$('#form').submit(function(event) {
event.preventDefault();
var data = new FormData(this);
$.ajax({
url: "post.php",
type: "POST",
data: data,
contentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
So, turns out I am just stupid.. It was actually working properly after all but I was checking if it works the wrong way. I was actually navigating to the php file by entering the url expecting to see my data printed on the php page. Finally, I checked the response of the POST request and it was working just fine.Thank you for your answers and I apologize for wasting your time.
try this,
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
method: 'POST',
data: {name: 'tony'},
success: function (response) {
$('#message').html(response);
}
});
});

How to save ajax "success" variable to php variable?

How can I save the "exportURL + data" data to a php variable? The ajax code is in the same php file, where I need to store that data in a php variable..
Currently its only showing an alert with the data in it, but I would like to store it in a php variable.
// URL to Highcharts export server
var exportUrl = 'https://export.highcharts.com/';
// POST parameter for Highcharts export server
var object = {
options: JSON.stringify(options),
type: 'image/png',
async: true
};
// Ajax request
$.ajax({
type: 'post',
url: exportUrl,
data: object,
success: function (data) {
//Save here in a php variable so i can use the value in the php code that follows in my file
}
});
If I understand you want to capture the data from an ajax submitted to an external server and write to your server, correct?
// URL to Highcharts export server
var exportUrl = 'https://export.highcharts.com/';
options = {};
// POST parameter for Highcharts export server
var object = {
options: JSON.stringify(options),
type: 'image/png',
async: true
};
// Ajax request
$.ajax({
type: 'post',
url: exportUrl,
data: object,
success: function (data) {
//Submit data from your server
// Ajax request
$.ajax({
type: 'post',
url: 'http://localhost/teste.php',//this your local file
data: {'data' : exportUrl+data},
success: function (data2) {
//Response from your server
//if your teste.php print response. echo "" or die("") ;
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
//this variable post contains your data sended from ajax
//print_r($_POST);
$data = $_POST['data']
?>

AJAX call to return values from PHP not working

I have a AJAX script which sends value to PHP script and to retrieve the value from the PHP script. The part where the script sends the value is working fine. Its the problem with the retrieving values. I am not able to figure out what is wrong.
AJAX code:
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
data: data,
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
PHP code:
<?php
$userAnswer = $_POST['name'];
echo json_encode($userAnswer);
?>
Please check whether "name" is posted before assigning the value to $userAnswer.
Both ajax scripts are sending to "ajax.php". In first ajax request "name" is posted, but in 2nd ajax request "name" is not posted.
To see warnings and errors, enable error reporting in php.
<?php
//To enable error reporting
ini_set('display_errors',true);
error_reporting(E_ALL);
data: {name: 145}
try this hope this will work.
Your nested AJAX call does not have the request type specified. The default is GET but your ajax.php is trying to find a POST.
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php',
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
type: "POST", //<-- added here
data: {name:data}, //<-- also required for POST
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
Set type:'POST' inside the second ajax call and try to use data1[0]. Also remember that you are sending a json string (that comes from the first ajax) with the second request. Basically you are encoding an encoded value,so when you receive the post value you should json_decode the post value

Using AJAX to pass variable to PHP and retrieve those using AJAX again

I want to pass values to a PHP script so i am using AJAX to pass those, and in the same function I am using another AJAX to retrieve those values.
The problem is that the second AJAX is not retrieving any value from the PHP file. Why is this? How can I store the variable passed on to the PHP script so that the second AJAX can retrieve it?
My code is as follows:
AJAX CODE:
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
PHP CODE:
<?php
$userAnswer = $_POST['name'];
echo json_encode($userAnswer);
?>
Use dataType:"json" for json data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.
SO, I recommend using one AJAX call and get the value with success.
example: in first ajax call
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
alert(data);
//or if the data is JSON
var jdata = jQuery.parseJSON(data);
}
});
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
data: data,
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call
In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.
Try this: var_dump($_REQUEST); and check if you're receiving the values.
you have to pass values with the single quotes
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: '145'}), //variables should be pass like this
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
try it it may work.......

Data not passing through AJAX

I am trying to pass a value of a button using some ajax to a separate file.
Here is my code.
$("input#downloadSingle").click(function() {
var myData = $("input#downloadSingle").val();
$.ajax({
type: 'post',
url:'singleDownload.php',
data: myData,
success: function(results) {
alert('works');
}
});
});
However, when I test out the next page by doing a var_dump on $_POST. I don't get any data back. Thoughts?
You're not specifying the name of the $_POST variable you're gonna get on the singleDownload.php file (unless that's part of the button's value), so you should try something like:
$("input#downloadSingle").click(function() {
var myData = "whatever=" + $("input#downloadSingle").val();
$.ajax({
type: 'post',
url:'singleDownload.php',
data: myData,
success: function(results) {
alert('works');
}
});
});
And make sure $_POST in your php file is the same whatever variable

Categories