Passing a variable from JavaScript to PHP through AJAX - php

I'm trying to pass the a variable from JavaScript to PHP using AJAX, but I'm unable to do so. Whenever I try to var_dump($_POST['winner_id']) it returns NULL. I've tried to check the AJAX call with Developer Tools in Chrome and it showed winner_id:0 - which is right.
Here is my code:
JavaScript
function ajaxCall() {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
( {
type: "POST",
url: "ajax.php",
data: {winner_id : winner_id},
success: function(response)
{ alert("The winner was passed!")}
}
);
};
ajaxCall();
PHP Code
<?php
session_start();
if(isset($_POST['winner_id']))
{
$winner_id = $_POST['winner_id']."";
var_dump($winner_id);
}
var_dump($_POST['winner_id']);
?>
If I do a var_dump($_POST) in the beginning of the PHP script then it gives me array(0) { }
I'm new to web development and have been trying to figure this out for hours now. Any hints would be much appreciated. Thanks!

Where are you intializing the winner_id.Either you have to pas it as an argument or intitialize it as aglobal variable.
function ajaxCall(winner_id) {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
({
type: "POST",
url: "ajax.php",
data: {"winner_id" : winner_id},
success: function(response)
{
alert("The winner was passed!");
}
});
};
ajaxCall(winner_id);

Where did you initiate value to winner_id? like
function ajaxCall() {
var winner_id = '123';
...
or if you initiated winner_id before calling ajaxCall() ,you should call ajaxCall() with parameters like ajaxCall($winnerid), which $winnerid is from your PHP
and then
function ajaxCall(winner_id) {
...

i guess you have to convert your winner_id to a string because php read zero (0) as null
function ajaxCall() {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
( {
type: "POST",
url: "ajax.php",
data: {winner_id : winner_id.toString()},
success: function(response)
{ alert("The winner was passed!")},
dataType: "json"
}
);
};
ajaxCall();

Related

How to get a single value of array which is returned by ajax call in success function using php

I want to display welcome message to the user with his name...on next page but without redirecting the page(url should not be changed) for the same I have used ajax call and stores data in MySQL database.It works fine,stores data,returns array of values in success function of ajax call,but how to get the first name from that array which is returned by ajax call..
Can anyone please help me for the same..
Thank you..
Here is the block of code...which I have used..
$('document').ready(function () {
$('#f1').submit(function (e) {
e.preventDefault();
$.ajax({
url: 'process.php',
type: 'post',
data: $('#f1').serialize(),
datatype:'json',
success: function (data) {
$('body').html('Welcome ' + data.fname);
}
});
This returns on next page as Welcome undefined
And if I modified it as-
$('document').ready(function () {
$('#f1').submit(function (e) {
e.preventDefault();
$.ajax({
url: 'process.php',
type: 'post',
data: $('#f1').serialize(),
datatype:'json',
success: function (data) {
$('body').html('Welcome ' + data);
}
});
This returns output like below-
Welcome 1{"fname":"test","lname":"test","pnum":"1234567890","email":"test#gmail.com","gender":"f","status":"married"}
Try this:
php function called by ajax:
<?php
// your code logic
$array = array('fname' => 'Pooja', 'lname' => 'Singh');
echo json_encode($array);
?>
ajax:
success: function(response) // here response is an json object so you have to parse it.
{
var data = JSON.parse(response);
// data.fname contains Pooja
// data.lname contains Singh, Show it where ever you required.
}

how to a php function which does not parameters from ajax?

I have js function to call a php function via ajax.
$("#history").click(function(){
$.ajax({
url: "./function.php",
type: "POST",
data: {"displayBookingHistory"},
dataType: "JSON",
success: function(data) {
console.log("hellosdasdasds");
$("#universalLogin").append(data);
}
});
})
and php function is
function displayBookingHistory () {
$html = " ";
....
echo json_encode($html);
}
and the call seems to be not successful, even when I try data: "displayBookingHistory",
Anyone knows solutions?
You have a syntax error in your JavaScript: an object needs to consist of a series of property:value pairs.
You can't call a PHP function using Ajax. Only a URL. You need to write your PHP so that it calls the function if you hit that URL.
You are completely ignoring $_POST in your PHP, so there is no reason for it to do anything with the data you are sending to it.
jQuery's AJAX method expects an object with key:value pairs (or a string) for the data field.
Like Quentin said you can't call PHP functions from AJAX, only complete pages. If you want to communicate "run this function" you will have to use $_POST data like this:
$("#history").click(function(){
$.ajax({
url: "./function.php",
type: "POST",
data: {function:"displayBookingHistory"},
dataType: "JSON",
success: function(data) {
console.log("hellosdasdasds");
$("#universalLogin").append(data);
}
});
})
Then in your PHP page:
if(isset($_POST["function"]){
$function = $_POST["function"];
if($function=="displayBookingHistory"){
displayBookingHistory();
}
}
How are you invoking that function?
May be you should have a switch statement that will check the data and call that function.
something like this
if(isset($_POST[data]){
switch($_POST[data]){
case "displayBookingHistory" :
displayBookingHistory();
break;
}
}
your have syntax error ajax send data.
data : {"property:value"} or data : {"property:value" , "property:value" , ...}
problem can be solved in 2 ways:
$ ("# history"). click (function () {
$ .ajax ({
url: "/function.php?action=displayBookingHistory",
type: "POST",
dataType: "JSON",
success: function (data) {
console.log ("hellosdasdasds");
$ ("# universalLogin"). append (data);
return false; //for disable a tag (link) click;
}
});
})
"action" is a parameter used for $_GET type to check php code.
Or
$ ("# history"). click (function () {
$ .ajax ({
url: "/function.php",
type: "POST",
data: {"action":"displayBookingHistory"},
dataType: "JSON",
success: function (data) {
console.log ("hellosdasdasds");
$ ("# universalLogin"). append (data);
return false; //for disable a tag (link) click;
}
});
})
"action" is a parameter used for $_POST type to check php code.
the best way is read a tag href attribute for work in javascript disable.
a tag :
linke
javascript :
$ ("# history"). click (function () {
$ .ajax ({
url: $(this).attr("href"),
type: "POST",
dataType: "JSON",
success: function (data) {
console.log ("hellosdasdasds");
$ ("# universalLogin"). append (data);
return false; //for disable a tag (link) click;
}
});
})
php code :
$action = isset($_GET["action"]) ? $_GET["action"] : "";
if($action == 'displayBookingHistory' )
displayBookingHistory();

Jquery .post() not passing data to PHP file

I am trying to pass an array through post to a php file. Here is my function in jQuery:
function callPHP() {
$.post("php/save.php", {
node: node
},
function (responde) {
console.log(responde);
});
}
And my save.php file has following content:
<?php
echo $_POST['node'];
?>
But I get an error that there's an undefined index 'node'. What is it that I am doing wrong?
try following
//define php info and make ajax call
$.ajax({
url: "php/save.php",
type: "POST",
data: { node: node },
cache: false,
success: function (response) {
}
});
Consider the below example. where info is an array
info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info:info},
url: "index.php",
success: function(msg){
$('.answer').html(msg);
}
});
.answer is the class of the element where you want to output your answer.

Get data from php script in javascript

I try to receive a PHP response in my JavaScript.
My PHP looks like this:
some code
if(...) echo "1";
else echo "2";
JavaScript:
function GetChoice() {
var returned="";
$.ajax({
async: false,
cache: false,
url: "http://mydomain.com/script.php",
type: "POST",
dataType:"text",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);
But GetChoice() returns nothing. What's wrong?
UPD: It works if javascript and php script are on the same server. My scripts in different domains.
Try this :
temp1.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function GetChoice() {
var returned = "";
$.ajax({
async: false,
cache: false,
type: "POST",
url: "http://localhost/temp2.php",
data: { name: "John"}
}).done(function( msg ) {
returned = msg;
});
return returned;
}
var r = GetChoice();
alert(r);
</script>
temp2.php
<?php
echo $_REQUEST["name"];
?>
its working....!
try this:
function GetChoice() {
var returned = "";
$.ajax({
async:false,
cache:false,
url:"http://mydomain.com/script.php",
type:"POST",
dataType:"text",
success:function (data) {
alert(data);
}
});
}
The problem is, in your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.
Here is explanation.
How do I return the response from an asynchronous call?
Luck,
GetChoice() will return nothing before the callback in success runs.
The callback, which is the function you define as the success paramater will not fire until the data have been requested from the server.
This is asyncronous (the A in AJAX) so the rest of the code with continue causing the GetChoice() function to return before the callback has been run
this is the script
<script type="text/javascript">
$.ajax({
async:false,
cache:false,
url:"http://path.com/to/file",
type:"POST",
dataType: "html",
data: 'data',
success: function(data){
alert(data);
}
});
and in your PHP file write this code
<?php
function test()
{
$str = 'This is php file';
return $str;
}
echo test();
?>
Make sure the path to the php file is correct AND add the script in another PHP file. Basically you need 2 files. Just tested this in my editor and works ..
function GetChoice() {
var returned="";
$.ajax({
url: "../script.php",
type: "POST",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);

JS jquery and ajax problem

Hi i have problem with some things
Here is the code
function get_char_val(merk) {
$.ajax({
type: "POST",
url: "char_info2.php",
data: { name: merk },
dataType: "html",
success: function(data){return(data);}
});
}
alert(get_char_val("str"));
when alert comes out it's output the undefined please help fast i'm making this two days xC
get_char_val does not return anything. The success callback needs to have alert(data) in it to return the data from AJAX.
$.ajax is asynchronous - meaning it doesn't happen in order with other code, that is why the callback exists.
Your return; statement will return the value to the anonymous function you pass into the success handler. You cannot return a value like this, you need to invoke another callback instead.
function get_char_val(merk, cb) {
$.ajax({
type: "POST",
url: "char_info2.php",
data: { name: merk },
dataType: "html",
success: function(data){cb.apply(this, data);}
});
}
get_char_val("str", function(data) {
alert(data);
});
You can either set the async:false config parameter in the ajax call options or use the call back.
Using Async:false -
function get_char_val(merk)
{
var returnValue = null;
$.ajax
(
{
type: "POST",
async:false,
url: "char_info2.php",
data: { name: merk },
dataType: "html",
success: function(data){returnValue = data;}
}
);
return returnValue;
}
alert(get_char_val("str"));
P.S: Note that making ajax calls synchronous is not advisable.
Since you do an asynchronous ajax call, the response of the server is handled in the "success" function. The return in your success function is useless, you should use the "data" parameter directly in the function
This should work. Use it like this.
function get_char_val(merk) {
var myReturnData= "";
$.ajax({
type: "POST",
url: "char_info2.php",
data: { name: merk },
dataType: "html",
success: function(data){myReturnData = data;}
});
return myReturnData;
}
alert(get_char_val("str"));
Just understand the problem with your piece of code. Use the return statement under the right function.

Categories