Accessing variable outside ajax body [duplicate] - javascript

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

Related

Array length empty [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm new to javascript and jquery, trying to learn, here I have this code to push values into the array, when I tried use length it shows me 0.
I know that there is guide out there, but still I don't understand what it actually means, can anyone help me out?
$.ajax({
url : "pokemonlist.txt",
dataType: "text",
success : function (data) {
var lines = data.split('\n');
for(var i=0;i<lines.length;i++) {
var arr = lines[i].split('"');
pokemon_id = arr[1];
pokemon_img = arr[3];
pokemon_name = arr[4];
pokemon_name = pokemon_name.trim()
pokemon_array.push([ pokemon_id, pokemon_img, pokemon_name ]);
}
}
});
console.log(pokemon_array.length);
You're calling console.log(pokemon_array.length) outside of the success callback, so it's actually called before the ajax call is done.
Here http://api.jquery.com/jquery.ajax/
Read about success and complete parameters.
Simple example:
$.ajax({
url: 'my-mega-link',
success: function (data) {
console.log(data);
}
});

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

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.
}

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 jsonp data to an array using Jquery [duplicate]

This question already has answers here:
Use variable outside the success function from an ajax/jquery call
(5 answers)
Closed 7 years ago.
I have created an jsonp request that retrieves data. The only problem is I cant seem to get the data in a array outside my loop:(
var lookbook_data = new Array();
$.ajax({
url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
dataType: "jsonp",
success: function(data) {
for(var i = 0; i<4; i++) {
lookbook_data[i] = data.posts[i].custom_fields.image1[0];
}
}
});
console.log(lookbook_data);
So when I console.log they array inside the look it output the data the way it should. However outside the function it does not. But I did decleare the variable outside so I really dont get why:(
Btw Sorry for messy codebock cant seem to get it right with 4 spaces:(
That ajax call is asynchronous, so you immediatly reach the last line of your code before it can finish.
You could make is synchronous (not recommended) with
async = 'false'
within the ajax call
or do something like this
$.ajax({
url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
dataType: "jsonp",
success: function(data) {
for(var i = 0; i<4; i++) {
lookbook_data[i] = data.posts[i].custom_fields.image1[0];
}
continueHere()
}
});
function continueHere() {
// rest of the code that handles your ajax call
}
var lookbook_data = new Array(),
XHR = $.ajax({
url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
dataType: "jsonp"
});
//anywhere else in your script you can call :
XHR.done(function() {
for(var i = 0; i<4; i++) {
lookbook_data[i] = data.posts[i].custom_fields.image1[0];
}
console.log(lookbook_data);
});
use this inside your for loop console.log(lookbook_data[i]); inside the success function
use console.log(lookbook_data); inside the success function

Categories

Resources