Array length empty [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'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);
}
});

Related

Display certain text before executing ajax [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 months ago.
I don't succeed with outputting this text before executing ajax. I know it has something to do with async/await, but after reading other posts and articles I still can't figure it out. Anyone able to help me with providing an updated code?
This is the output (Calculating now...) I want before execution:
$(this).parent('td').parent('tr').find('td span.google').text('Calculating now...');
Full code:
$(function(){
$('.calculate').click(function(){
$(this).parent('td').parent('tr').find('td span.google').text('Calculating now...');
var total_distance = 0;
$(this).parent('td').parent('tr').find('td span.tripleg').each(function() {
var origin = $(this).attr('origin');
var destinations = $(this).attr('destinations');
$.ajax({
type: "GET",
url: 'includes/calculate_distance.php?action=distance_analysis',
data: {"origin": origin, "destinations": destinations, "google_api_key": google_api_key},
async: false,
success: function(result) {
total_distance = total_distance + parseFloat(result);
}
});
});
$(this).parent('td').parent('tr').find('td span.google').text(total_distance.toFixed(2));
});
});
Many thanks in advance!

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

Javascript Array Variable Scope [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 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!

javascript function that return a value from ajax [duplicate]

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.

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