Javascript and Ajax - Unable to transfer variable content [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Variable doesn't get returned from AJAX function
(2 answers)
Closed 9 years ago.
I am currently doing some tests using the following code:
function updateCurrentTime() {
var HeaderDate;
$.ajax('/', {
url: "http://www.google.com",
type: 'HEAD',
success: function(r,status,xhr) {
HeaderDate = xhr.getResponseHeader('Date');
}
});
var curTime = new Date(HeaderDate);
}
Unfortunately at the following line:
var curTime = new Date(HeaderDate);
I am not able to retrieve the variable content of the HeaderDate in the AJAX code.
The goal is to get time from a different location than the local computer running the script.
I even tried using global variables without any success.
Can you help me out please?
Thanks a lot for your time and help.

It is because curtime is set BEFORE the ajax returns.
Something like the following would be better, but the takeaway here is that you need to have your application updating when the ajax returns, so within the success callback.
function updateCurrentTime() {
var HeaderDate, curTime;
function setCurrentTime(time){ curTime = new Date(time);}
$.ajax('/', {
url: "http://www.google.com",
type: 'HEAD',
success: function(r,status,xhr) {
setCurrentTime(xhr.getResponseHeader('Date'));
}
});
}

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

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 do I execute jquery function after the db is updated by php? [duplicate]

This question already has answers here:
jQuery ajax success callback function definition
(8 answers)
Closed 7 years ago.
Okay, so what I'm trying to do is delete a row from my DB. Then update my list in html/php.
function deleteThis(blogid) {
var result="";
$.ajax({
url: 'deleter.php',
type: 'POST',
data: { id: blogid },
success:function(data) {
result = data;
alert(result);
}
});
if (result!=""){
$("#contentContainer").html(showAll("contentAllBlogs"));
};
};
Using this code (above), I am able to successfully delete data from my database. My problem is reloading the #contentContainer after the DB has been updated.
If I use setTimeout, and wait a few seconds before triggering this code (below)
$("#contentContainer").html(showAll("contentAllBlogs"));
It actually works, my list gets updated. But I don't want to use setTimeout. Is there a way to trigger this code after the DB is finished updating?
Please, help me. Thank you in advance.
you can not access result data out the ajax function because
in if() statement result value is undefined.
function deleteThis(blogid) {
var result="";
$.ajax({
url: 'deleter.php',
type: 'POST',
data: { id: blogid },
success:function(data) {
result = data;
displayData();
}
});
function displayData(){
$("#contentContainer").html(showAll("contentAllBlogs"));
}

Categories

Resources