variable appearing blank after ajax, but has value within ajax success function - javascript

As the title says, I have an ajax function that I am using to call a function that assigns a value to a variable in js from my mysql db. On success, I can print the echoed data out and it appears in the console fine. However, calling the variable after the ajax call yields an empty variable. What is going on?
Code below:
request = $.ajax({
url: "/fans/get_url_tag",
type: "post", success:function(data){url_tag = data; console.log(url_tag); //prints the correct value},
data: {'fbid': result.id} ,beforeSend: function(data){console.log(data);}
});
//prints nothing
console.log(url_tag)

Sounds like the scope is wrong.
Maybe just declare it before your $.ajax call:
var url_tag;
request = $.ajax({
url: "/fans/get_url_tag",
type: "post", success:function(data){url_tag = data; console.log(url_tag);},
data: {'fbid': result.id} ,beforeSend: function(data){console.log(data);}
});
console.log(url_tag); //Should print the same value

You need to put the console.log in the callback function.

Related

Variable lost in ajax request

I'm facing a strange behaviour when trying to pass a variable as parameter to a nested ajax request callback:
$('form').on('submit',function(e){
$.ajaxSetup({
header:$('meta[name="_token"]').attr('content')
})
e.preventDefault(e);
$.ajax({
type:"POST",
url:dest_url,
data:$(this).serialize(),
dataType: 'json',
success: function(data){
if($.isEmptyObject(data.error)){
// performing some actions
// at this point, data.id contains my id
// We call an other function,
// which performs an other ajax request,
// with data.id as parameter
listRefresh(data.id);
}else{
// error message
}
},
error: function(data){
// error message
}
})
});
function listRefresh(id){
console.log(id); // At this point, id contains my id
$.ajaxSetup({
header:$('meta[name="_token"]').attr('content')
})
var src_url = location.href + '?id='+id;
$.ajax({
url: location.href,
type: 'GET',
cache: false
})
.done(function(id) {
console.log(id);
// At this point the console outputs
// all my html code in place of id
// I tried to pass data, response, id, but still the same issue
})
.fail(function() {
//error message
});
}
As said in code comments above, in the listRefresh ajax done callback, my variable seems to disapear and the console.log outputs my entire html code in the console...
I've never seen something like this. Do you have an explanation of why, and how could I pass my id as parameter to the ajax callback ?
The first argument passed to the function in done is the response from the AJAX request. It doesn't matter what you call the variable, that's what will be passed to that function.
You can capture the value in the closure however, simply give it another name and assign it to a local variable. Something like this:
done(function(response) {
var theId = id;
// "response" contains the response from the server.
// "theId" contains the value of `id` from outside this function.
})
The parameter of the .done() method is the response of the AJAX call. If your call returned a HTML page, the id variable got all of the html string assigned to it.
To keep the id in its variable simply use another one like:
.done(function(data) {
console.log(data)
console.log(id);
});

jQuery ajax request only returns value on second call

I'm trying to get data from a php using jQuery's $.ajax method.
This is my code right now:
var ajaxresult = null;
function myFunc() {
$.ajax('ajaxtest.php',{
type: 'get',
data: '',
success: function(data) {
ajaxresult = data;
}
});
console.log(ajaxresult);
}
$('button').click(function(){
myFunc();
})
My problem is this:
The first time I call myFunc() (when I click the button) it logs null to the console, after that if I click again it returns the expected value.
What could cause this and how could I fix it to return the expected value the first time it's called?
Ajax is asynchronous, so the first time you click, the console log happens before the ajax call has completed, and it logs null.
The second time you click, the same thing happens, but the variable is global, so it now holds the value from the previous ajax call, and that's what's logged, the value from the previous call, not the value from the current call.
It should look more like this, the data is only available inside the callback
function myFunc() {
$.ajax({
url : 'ajaxtest.php',
type : 'GET',
data : '',
success: function(data) {
var ajaxresult = data;
console.log(ajaxresult);
}
});
}
$('button').click(myFunc);

Jquery: Variable not initialized in callback?

I have the following code snippet in Javascript-Jquery:
var result = "";
$.ajax({
type: 'POST',
url: 'update.php',
data: { 'val': $val }
})
.done(function(data) {
alert(data); // shows right response
result = data;
alert(result); // shows right response
});
alert(result); // shows nothing
Even though I initialized result in the callback, I get nothing when I alert the result variable (it is still "")? Why is this?
This is because the ajax call is run asynchronously. Just because the second alert is after the ajax call, you still have to either a: write a callback method to fire when the call completes or, b: complete the ajax call synchronously. See jquery ajax documentation for the async property and its description.
Is is simple. The alert(result) code is executed before the done callback. So, the result variable is empty. The done callback is called asynchronously after the alert call.
Hope it helps.
This becasue the mode of ajax now you use is the Asynchronous ...i have a example for you that it's as follow:
var result = "";
$.ajax({
type: 'POST',
url: 'update.php',
data: { 'val': $val' }
}).done(function(data) {
alert(1, data); // shows right response
result = data;
alert(2, result); //shows right response
});
alert(3, result) // shows nothing
if you want to use the Synchronous...look at the doc for async variable
i hope it's useful to you:)

javascript & jQuery scope question

I have the following method:
function priceRange(FESTIVALID){
jQuery.ajax({
url : '/actions/festheads.cfc?method=getPriceRangeByGUID',
type : 'POST',
data : 'FESTIVALID='+FESTIVALID,
dataType: 'json',
success : function(data) {
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
}//success
});//ajax;
//
return formatedPriceRange;
};
The second console.info correctly displays the formatedPriceRange,
but outside the function is undefined.
how can I access this variable out side the priceRange function?
Thanks
It's normal, that's how AJAX works. It's asynchronous, meaning that the jQuery.ajax function returns immediately and in this case formatedPriceRange hasn't yet been assigned a value and once the server responds (which can be for example 10 seconds later), the success callback is invoked and the variable is assigned a value.
So always consume the results of your AJAX requests inside the success callback function.
You also have the possibility to pass the async: false option to your jQuery.ajax call which will perform a synchronous request to the server and block until the result is retrieved. Obviously this will lead to your browser freezing during the execution of the request. So it would no longer be AJAX (Asynchronous Javascript And Xml) but SJAX (Synchronous Javascript and Xml).
You have to make sure that the AJAX request finishes before you access the price range data.
You need to expose the price range data outside the scope of the success function.
Here's how you can do it:
function priceRange(FESTIVALID, callback) {
jQuery.ajax({
url: '/actions/festheads.cfc?method=getPriceRangeByGUID',
type: 'POST',
data: 'FESTIVALID=' + FESTIVALID,
dataType: 'json',
success: function(data) {
console.info("AJAX:qPrices", data.MINPRICE);
formatedPriceRange = '$ ' + data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
callback.call(this, formatedPriceRange);
} //success
}); //ajax;
}
var myFestivalID = 1;
priceRange(myFestivalID, function(priceRange) {
// this code runs when the ajax call is complete
alert('The formatted price range is:' + priceRange);
});
how can I access this variable out
side the priceRange function?
Like Darin said, you have to use your results in the success callback function.
Assuming you're using your current function like this:
var range = priceRange(festivalId);
// ... doing stuff with range variable
You'll want reorganize your code so that anything you do with the range variable stems from the success callback. For example, you can create a function to handle updating the UI with the new range:
function handleRangeVariabe(range) {
/// ... do stuff with range variable
}
Call it from success:
success: function(data) {
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
handleRangeVariable(formatedPriceRange);
}
Flower the steps of sample Code:
//declare function
function priceRange(FESTIVALID, functionCallBack){
//1º step
jQuery.ajax({
url : '/actions/festheads.cfc?method=getPriceRangeByGUID',
type : 'POST',
data : 'FESTIVALID='+FESTIVALID,
dataType: 'json',
success : function(data) {
//3º step, because this function will only trigger when server responds to request
//handle data in other function
functionCallBack(data);
}//success
});//ajax;
//more code
//2º step
//no return value, because this method no know when the data will return of server
//return formatedPriceRange;
};
var formatedPriceRange;
//using function
princeRange(1 , function(data){
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
});

Variable modified in an ajax request is not visible after having been executed

My variable is Global, but she doesn't display the same result :
function checkLiveRdv(salle, jour, dateus, heure)
{
var resu;
var urlaction = myUrl;
$.ajax({
type: "POST",
dataType: "json",
url: urlaction,
data: myDatas,
success: function(message)
{
data = $.parseJSON(message);
if(data['nb']==1)
resu = "ok";
else resu = "pasok";
//this alert display the good result
alert (resu);
}
});
//this alert display 'undefined', why ???
alert(resu);
}
I don't know why resu doesn't keep the data :/
First, your resu variable is not global. It is local inside the scope of the checkLiveRdv function. Global variables in javascript are declared without the var keyword. However, omitting global variables is a good practice.
The first alert which appears displays a yet valueless undefined resu. The asynchronous $.ajax finishes later and as it fills the value of resu, it gets displayed correctly.
I would leave the ajax call asynchronous as it is now. And work with resu only inside the ajax callback as it gets its value inside it.
That is becouse you are not waiting for the $.ajax() call to complete.
If you need synchronous requests, set the sync option to false:
$.ajax({
type: "POST",
async: false,
...
It is because $.ajax() in this case is asynchronous. Modify $.ajax() to include async: false:
$.ajax( {
type : 'POST',
dataType: 'json',
url : urlaction,
data : myDatas,
async : false,
success : function(message) {
data = $.parseJSON(message);
if(data['nb']==1)
resu = "ok";
else resu = "pasok";
alert (resu);
}
} );

Categories

Resources