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 problem with array variable scope in Javascript. Here's my code
var features = new Array();
var x = 0;
$.ajax({
async: true,
url: domain + "client/applications/getFeatures",
dataType: 'json',
success: function(data) {
if (data.code == 200) {
$.each(data.data, function(i, val) {
features[x] = val.features_value;
x++;
});
}
}
});
alert(features[0]);
The result of the pop up always "undefine". Do you have solutions ? Thank you
You problem isn't with variable scope, it's with async code.
Your alert is fired before the success callback, so features hasn't been set yet. Do something like this instead:
$.ajax({
// ... other AJAX opts
success: function(data){
var features = new Array();
if(data.code == 200){
var x = 0;
$.each(data.data, function(i, val){
features[x]=val.features_value;
x++;
});
}
alert(features[0]);
}
});
If you need to use the alert(); (eg, you're not using it for debugging) then you'll need to include it within the success function because it's asyncronous and needs to wait until it gets the response before showing the value!
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I need lines to be a global array but when I use console.log to compare values inside the function and outside the function, the inside one works fine but the outside one remains empty. Am I missing something here?
var lines = new Array();
$.ajax({
type: "GET",
url: "posts_replied_to.txt",
success: function(content) {
console.log("success");
lines = content.split('\n');
console.log(lines);
},
error: function() {
console.log("error");
}
});
console.log(lines);
The problem here is not regarding global variables. Its the asynchronicity problem.By the time the console.log() outside your ajax request is called, the ajax success callback is not called.Thats why you won't get the right value.
async function doAjax() {
return await $.ajax({
type: "GET",
url: "posts_replied_to.txt"
});
}
let lines = await doAjax()
lines = content.split('\n')
console.log(lines)
Try this code using
Async to get the expected result.
Yes,AJAX is asynchronous function.So, in outside 'console.log(lines)' command run before AJAX.
You can AJAX asyn:false
What does "async: false" do in jQuery.ajax()?
Before your GET response come your second console.log code also execute due to ajax is not async. Change as below,
var lines = new Array();
$.ajax({
type: "GET",
url: "posts_replied_to.txt",
async: false,
success: function(content) {
console.log("success");
lines = content.split('\n');
console.log(lines);
},
error: function() {
console.log("error");
}
});
console.log(lines);
Try using promise object returned by ajax call.
var lines = new Array();
var promise_obj = $.ajax({
type: "GET",
url: "posts_replied_to.txt"
}).promise();
promise_obj.done(function(response)
{
lines = response.split('\n');
console.log(lines);
// Rest of your logic goes here where you want to use lines.
});
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);
}
});
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 function that makes a check through AJAX and returns a result. The result is caught and placed within a variable, but I can't get it from inside the AJAX to show in another area. Can anyone help me please?
JS:
var get_cidade_frete = function(){
if($('#senderCity').val() != ''){
var frete_patinete_branco = 0;
var frete_patinete_preto = 0;
var frete_val_patinete_branco = $('select[name="patinete_branco_qnt"]').val();
var frete_val_patinete_preto = $('select[name="patinete_preto_qnt"]').val();
$.ajax({
type: 'POST',
data: $('#senderCity').serialize(),
url: './ajax/frete_calc.php',
dataType: 'json',
beforeSend: function(data){
},
success: function(data){
var get_frete_patinete_branco = Number(data[0]['valor']);
var get_frete_patinete_preto = Number(data[1]['valor']);
if(frete_val_patinete_branco != 0){
frete_patinete_branco = get_frete_patinete_branco * frete_val_patinete_branco;
}
if(frete_val_patinete_preto != 0){
frete_patinete_preto = get_frete_patinete_preto * frete_val_patinete_preto;
}
total_produtos_frete = frete_patinete_branco + frete_patinete_preto;
return total_produtos_frete;
},
});
}
}
Show variable:
$('#senderCity').change(function (){
var x = get_cidade_frete();
console.log(x);
});
Pass in a callback function to the "get_cidade_frete" function, the callback then should do whatever you need to be done with the variable.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Can you help with my problem. I want to make a function that will return list of doctors in different spicialization.. this is my code the problem is this code the function doctorlist returns emtpy value. what is the wrong with my code.
can you help me to fixed my problem please.
$(document).ready(function () {
$("#loaders").append("<center><img src='images/ajax-loader.gif'></center>");
doctorSpecialty();
});
function doctorSpecialty(){
$.ajax({
url: "http://localhost:8080/m-help/apps/json_special.php",
dataType: 'json',
async: true,
success: function(data) {
$("#list").empty();
$.each(data.result, function(){
var specialty = doctorList(this['specialization']);
$("#list").append("<li><a href='doctor-special.html?special=" +this['specialization']+ "' style='padding-left:10px'>" +this['specialization']+ ""+specialty+"</a></li>");
$("#loaders").fadeOut("fast");
});
}
});
}
function doctorList(e){
var specials = e;
var retSpecial = "";
$.ajax({
url: "http://localhost:8080/m-help/apps/json_special-doctor.php?s="+specials,
dataType: 'json',
async: true,
success: function(data) {
$.each(data.result, function(){
retSpecial = this['docFname'];
});
}
});
return retSpecial;
}
Anyone can help me to fixed this code for please.
The second call can not be async = true, since the loop continues and uses the answer (which has not arrived yet).
You should make the second async:false
OR
Use promises in the second call which will fill in the specialization and you need to cancel the DOM manipulation in the first ajax call.
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