How can I access AJAX defined variable gloabally? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I created a variable in AJAX success function which I want to use for another AJAX call outside that function. I tried to store it with local storage and then use it but could not access the variable. Any idea as to how can I access it?
Here is the code:-
var c_id = 110;
$.ajax({
type : "POST",
dataType : 'json',
data : {'id':c_id},
url : 'http://127.0.0.1/Student Back End/sbms.php',
success : function(data){
var quant_presta = data.quantity;
localStorage.setItem('Presta_Quant',quant_presta);
console.log(localStorage.getItem('Presta_Quant'));
},
error : function(data){
//console.log(data.name.quantity);
$('#fetch_error').show();
$('#fetch_error').fadeOut(5000);
}
});

Show the code ..
$.ajax({
url : '',
success: function(data){
myFunction(data);
}
});
function myFunction(data){
// do the processing here. You can access this from all ajax calls.
}

Related

Accessing variable outside ajax body [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have an ajax request and I want to access an array defined in the ajax body outside its body.I am new to javascript so any help would be appriciated.This is my ajax request
$.ajax({
type:"GET",
url: url ,
success: function(finalresult) {
arr=[]
for(var i=0;i<finalresult.routes[0].geometry.coordinates.length;i++)
{
arr.push(finalresult.routes[0].geometry.coordinates[i])
global_data =arr.push
}
}
});
How can I access array arr outside the ajax body?
You can access it by creating a variable outside the ajax and setting its value inside the success function. Also note you can get its value only after the ajax & its success has finished its execution. For this you can use ajax done. Otherwise it is always going to give an empty array
let arr = [];
$.ajax({
type: "GET",
url: url,
success: function(finalresult) {
for (var i = 0; i < finalresult.routes[0].geometry.coordinates.length; i++) {
arr.push(finalresult.routes[0].geometry.coordinates[i])
global_data = arr.push
}
}
}).done(function() {
console.log(arr)
});

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) { ... } );

Get value from php to javascript using ajax [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 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
}

Returning value from javascript 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 created a javascript object and im trying to fetch som data from it.
Im using jquery ajax to fetch send some values and then returing them from a php script.
this works, but when i try to use an instanse of my javascript object to dispaly the value i get 'undefined'.
Object:
var getDBresults = (function () {
function getResult(url,TableName ,callback){
$.ajax({
url: url,
type: 'POST',
data: {
'table':TableName,
},
success: function(data){
callback(data);
},
error: function(event){
alert(event.error);
}
});
}
return {
getAllVideoes: function(){
getResult("getAllResults.php", "videoer", function(data){
console.log(data); //Works
return data;
});
},
}
})();
in my other script:
var obj = getDBresults;
var data = obj.getAllVideoes(); //this runs, and produce the log showed above
console.log(data) //results in undefined
console.log(obj.getAllVideoes()) //results in undefined
Maybe you can use callbacks it will solve your async problems: http://recurial.com/programming/understanding-callback-functions-in-javascript/

Categories

Resources