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:)
Related
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.
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);
i have small issue with exchanging data in between methods in a JavaScript object (class):
var TEST = (function () {
var TEST = function() {
};
TEST.prototype.get = function() {
$.ajax({
type: "GET",
url: "http://test.com/getall",
dataType: "json",
success: function (data) {
return data; // if i console log this i will get a json obj
}
});
};
TEST.prototype.parse = function(data) {
$.each(this.get(), function(k, v){
console.log(v);
});
};
return TEST;
})();
so i am trying to call one method in the each statement in another method. the issue is that
the response is undefined.
i also tried it like this, but with he same result
var testing = new TEST();
var get = testing.get();
testing.parse(get);
What am i missing? how can i return the data from this.get to be used in this.parse.
thanks
$.ajax() per default is asynchronous. That means, that the execution of your function get() wont wait until the request is finished. Hence you return no value from it, which results in undefined being returned.
In order to have your get() function be able to return a value, you would have to do the request in a synchronous way and set a variable in the outer function (as success itself is just another function, whose return value is not caught):
TEST.prototype.get = function() {
var result;
$.ajax({
type: "GET",
url: "http://test.com/getall",
async: false, // this is the important part!
dataType: "json",
success: function (data) {
result = data;
}
});
return result;
};
EDIT
As mentioned by #pebbl, this will halt the execution of all your scripts, until the request is done. Hence your whole page will be blocked for the time being.
The general approach is to use callbacks in such cases, which will be executed once the requests finished. So in your case something like this:
TEST.prototype.get = function( cb ) {
$.ajax({
type: "GET",
url: "http://test.com/getall",
dataType: "json",
success: function (data) {
cb( data );
}
});
};
with later on calling like this:
var testing = new TEST();
testing.get( function( data ) {
testing.parse( data );
});
You can't construct your function this way as you are relying on an asyncronous call, which will return it's result outside of the normal execution flow. The only way you can actually receive the result of your .get function is to use a callback.
Put simply your value isn't being returned from the .get function, it's being returned from the callback you are passing into jQuery's .ajax method.
You'd be far better off redesigning your code so as to still support the asyncronous call -- rather than disabling async.
A rough idea is to change your parse function like so:
TEST.prototype.parse = function(data) {
this.get(function(result){
$.each(result, function(k, v){
console.log(v);
});
});
};
And to change your get function accordingly:
TEST.prototype.get = function(callback) {
$.ajax({
type: "GET",
url: "http://test.com/getall",
dataType: "json",
success: callback
});
};
The above is just a quick example, you'd be wise reading up on the following jQuery topics:
http://api.jquery.com/promise/
http://api.jquery.com/category/deferred-object/
If you design your code around the promise pattern you'll find it complicated at first, but it gives you a lot of power in your code -- and gets around the whole callback stacking madness you can end up with when dealing in ajax calls.
Whilst it's not entirely clear from the jQuery.ajax documentation, this function returns a jqXHR object which implements the promise interface. So this means you can use the promise methods done, always and fail.
http://api.jquery.com/jQuery.ajax/
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);
}
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);
});