Get value from php to javascript using ajax [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have the following ajax script
dataString = 'cipher'; //
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
returnedvalue = result //I wanted to store the value returned by php in this variable
alert(returnedvalue);
and the tokenize.php is
$data = json_decode(stripslashes($_POST['data']));
return $data; //Pass this value as ajaxs response
But im not able to get this.When I checked in the console I get error uncaught:result is not defined.
Im new to query,searched on google and done upto this.
The json is not necessary,all I wanted to do is pass a value to php and process it and give a rssponse back to teh javascript so that i can use it in the javascript

You are passing just string(dataString = 'cipher';) into ajax file. There is no need to JSON.
To use echo for return values from AJAX file.
Update in JS:
dataString = 'cipher'; //
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(result) { //just add the result as argument in success anonymous function
var returnedvalue = result;
alert(returnedvalue);
}
});
Update in PHP file:
$data = stripslashes($_POST['data']);
echo $data;

You need to pass the parameter into the anonymous function for the success event.
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}

Related

How to return data from ajax call JQuery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a webapi in asp.net that gives me back JSON code. I want to access this with JQuery in a php-website.
I have this JQuery code to get the data from the webapi:
$.ajax({
type: 'GET',
url: 'localhost/webapi/api/data'
}).done(function (data) {
});
How can I return the value of 'data' to a global variable? So that I have a list of objects where I can loop through with navigation buttons.
Example:
When I click on the nextButton, I want to get the value of data[1].Text.
$('#nextButton').click(function() {
data[1].Text;
});
Perhaps like this:
var dataContainer = {}; // if you work with strings use ''
$.ajax({
type: 'GET',
url: 'localhost/webapi/api/data'
}).done(function (data) {
dataContainer = data;
});
$('#nextButton').click(function() {
if(dataContainer != {}){ // for strings != ''
// use dataContainer
}
});

Ajax global variables or synchronous AJAX [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I want to get data from another page using AJAX. I also want to wrap this AJAX call into my "user defined function".
But I can not write like this:
function func(){
var tmp;
$.ajax({
url: 'url',
type: "POST",
dataType: "json",
success: function (data) {
tmp=data;
}
});
return tmp;
}
because AJAX is asynchronous and this code returns - "undefined".
When AJAX async param set to false
var tmp=$.ajax({...});
possible do the trick.
I also can create some global variables and write like this:
function setMyVariable(){
$.ajax({
...
success: function (data) {
myGlobalVariable=data;
}
});
}
The question is - Is it good practice to use global variables in this case?
Or it is completely wrong and I need search something else
The best practice would be to return the promise from $.ajax:
function func(){
var tmp;
return $.ajax({
url: 'url',
type: "POST",
dataType: "json",
});
}
Then you can do function().done(function(result) { ... } );

AJAX response into an object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a stringified array of objects in a database that I'm retreiving with an $.ajax call. I'm trying to use a callback function to get that data into an array outside of my ajax function.
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
data: "",
dataType: 'JSON',
success: dataHandler
});
};
function dataHandler(data){
console.log(JSON.parse(data));
return JSON.parse(data);
}
var loadedMap = getMap();
console.log(loadedMap);
The console.log inside of the dataHandler function shows up in my Javascript console as a standard Array (clickable, can view all the data). The console.log at the very end shows up in the console as [object Object]. I can see the actual data inside of that object in a "responseJSON" field, but I can't seem to correctly get that into the loadedMap array.
What am I missing here?
Edit: I feel like my question is different from all of the answers to other questions. Mine seems to be more of a scope problem. A lot of the answers advocated the .done and .fail ways to handle AJAX.
var loadedMap = [];
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
dataType: 'JSON',
});
};
getMap().done(function(r) {
if (r) {
loadedMap = r;
} else {
console.log("No data");
}
}).fail(function(x) {
console.log("error");
});
console.log(loadedMap);
This code successfully gets the array where "loadedMap = r", but when you console.log the loadedMap on the outside, its undefined. How can we get the actual data to be outside the AJAX functions?
The function getMap does not return the response, it just calls dataHandler when the response arrives.
create a global variable and assign the vallue of the JSON.parse(data) to that variable. :
var myData;
function getMap(){
...
});
};
function dataHandler(data){
console.log(JSON.parse(data));
myData = JSON.parse(data);
}
getMap();
JQuery's AJAX returns a promise, so you can either go the callback route, as it looks like you were trying to do, or you can simplify it with promises:
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
data: "",
dataType: 'JSON',
success: dataHandler
});
};
getMap().then(function(data){
loadedMap = JSON.parse(data);
console.log(loadedMap);
});

Save parsed JSON data into Variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have this ajax request call to a json supported link (url1):
$.ajax({
type : "GET",
dataType : "json",
url : url1,
success: function (data) {
c1lat1 = [(data[0].boundingbox[0]),(data[0].boundingbox[2])];
alert(c1lat1);
}
});
This works perfectly fine, and the alert does give the number I want. However, if I try this:
$.ajax({
type : "GET",
dataType : "json",
url : url1,
success: function (data) {
c1lat1 = [(data[0].boundingbox[0]),(data[0].boundingbox[2])];
}
});
alert(c1lat1);
It gives me an empty alert box, and therefore it looks like it's not saving the value into the variable into the request.
How can I get around this as I need that value retrieved?
Thanks!
Since ajax is async by default, you have two options-
Alert the variable in the callback. You must proceed after you get the result in the callback-
$.ajax({
type : "GET",
dataType : "json",
url : url1,
success: function (data) {
c1lat1 = [(data[0].boundingbox[0]),(data[0].boundingbox[2])];
alert(c1lat1);
}
});
Make the call synchronous using async: false, this will make your call synchronous, and the control will come after $.ajax();
$.ajax({
type : "GET",
async: false,
dataType : "json",
url : url1,
success: function (data) {
c1lat1 = [(data[0].boundingbox[0]),(data[0].boundingbox[2])];
}
});
alert(c1lat1);
Reference
1) it's scope problems. c1lat1 inside success is local variable. Define it globaly.
2) success is async, so your alert happens before response from server, so no variable is set yet. move alert to success

jQuery ajax return value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
How can I return the value "pinNumber" from jquery ajax so I can append it outside of the ajax. Here is my code
var x = pinLast + 1;
for(i=x;i<=pinMany;i++) {
var i = x++;
var cardNumber = i.toPrecision(8).split('.').reverse().join('');
var pinNumber = '';
jQuery.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator",
async: false,
success: function(msg){
var pinNumber = msg;
return pinNumber;
//pin number should return
}
});
jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+'');
// the variable pinNumber should be able to go here
}
Please ask me if you don't understand.. ^^ thanks
AJAX is asynchronous by default, you cannot return a value from the callback without making a synchronous call, which you almost certainly don't want to do.
You should supply a real callback function to the success: handler, and put your program logic there.
var pinNumber = $.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator",
async: false
}).responseText;
jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+' ');
It has to do with variable scope. The local variable pinNumber you create is not accessible outside its wrapping function.
Perhaps declare pinNumber globally or if it'll do the trick, simply stick your .append() inside your success function.
var _successEvent = function(response){
$('.pin_generated_table').append(cardNumber + ' = ' + response);
};
$.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator"
}).done(_successEvent);
You can use this example:
window.variable = 'some data';
This make you variable global and you can access to this from anywhere
Here is the simple solution.
//---------------------------Ajax class ------------------------------//
function AjaxUtil()
{
this.postAjax = function(Data,url,callback)
{
$.ajax({
url: url,
async: true, //must be syncronous request! or not return ajax results
type: 'POST',
data: Data,
dataType: 'json',
success: function(json)
{
callback(json);
}
});
}//--end postAjax
}
//--------------------------------End class--------------------//
var ajaxutil = new AjaxUtil();
function callback(response)
{
alert(response); //response data from ajax call
}
var data={};
data.yourdata = 'anydata';
var url = 'data.php';
ajaxutil.postAJax(data,url,callback);

Categories

Resources