Variable lost in ajax request - javascript

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

Related

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

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.

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 - Difference between replaceWith making ajax call or vice versa

Suppose I want to make an ajax call to the server and use the response to replace a section of existing document content. Would there be any reason to choose one of these methods over the other?
Option 1 - make the ajax call, and perform the replaceWith from the error/success functions. Example:
$.ajax({
type : 'GET',
url : '/some/path/here',
success : function(data) {
// process data here
$('#container').replaceWith(processedData);
}
});
Option 2 - call replaceWith, passing in a function that makes the ajax call. Example:
$("#container").replaceWith(function(){
var responseData;
$.ajax({
type : 'GET',
url : '/some/path/here',
success : function(data) {
// process data here
responseData = processedData; //
}
});
return responseData;
});
Second one is not an option. When you take the function out;
function(){
var responseData;
$.ajax({
type : 'GET',
url : '/some/path/here',
success : function(data) {
// process data here
responseData = processedData; //
}
});
return responseData;
}
This will return undefined. Cause, when the time function runs and returns, reponseData is undefined. Only, sometime in future, success function executes and sets responseData. However, your replaceWith code has already finished executing.
Go with option 1.
Option 1 is your only choice, as option 2 would not work as the call would execute asynchronously. This means your function would never return anything.
If you are looking to externalise the processing of the data returned from your AJAX call, just set the success parameter as a reference to the function you want to execute:
$.ajax({
type: 'GET',
url: '/some/path/here',
success: processData
});
function processData(data) {
// process data here
$('#container').replaceWith(data);
}

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

Reusing 'data' passed in the jquery-ajax call

I'm using jquery's .ajax() method on a button click.
I wanted to know if there a way in whcih I can use the data that I passed in the data-part of the AJAX call in my success() function.
This is my code,
$.ajax({
url: //my URL here..
type: 'POST',
data:{
projDets : projDetailsArray,
},
datatype:'html',
error: function(){
alert('Error loading Project Information');
},
success: function(html){
//I wanted to re-use 'projDets' that I'm passing in the
//'data' part of my code..
}
});
Any help will be appreciated.
Thanks
You could wrap the $.ajax parameter in a closure, set up the "data" value as a local variable, and then reference it both for the "data" value and inside the "success" function:
$.ajax(function() {
var data = {
projDets: projDetailArray
// ...
};
return {
url: // your URL here..
type: 'POST',
data: data,
datatype:'html',
error: function(){
alert('Error loading Project Information');
},
success: function(html){
// just reference "data" here!
}
};
}());
Pritish - a quick and dirty way would be to store the json array in a jquery .data() object and then retrieve it as required.
1st, set the data: element to a named array:
// set 'outside' of the $ajax call
var projDetailsData = {projDets : projDetailsArray};
// now store it in a div data object
$("#targetDiv").data("myparams", projDetailsData);
// the data part of the $ajax call
data: projDetailsData,
to retrieve it again:
// get the value stored and call the $ajax method again with it
var projDetailsDataCopy = $("#targetDiv").data("myparams");
worth a try maybe!!
jim
[edit] - also, you could of course store the array in a module level vaiable -yuk!! :)

Categories

Resources