I'm using the google maps api and I've noticed a programmatic behavior that I'm not familiar with in JavaScript:
function success(pos) {
// ...do something with pos.
}
navigator.geolocation.getCurrentPosition(success);
In the example above it appears as though the success function is passed a 'pos' argument from thin air and the success function isn't invoked inside the getCurrentPosition argument via parentheses. I would expect to see something like this:
function success(pos) {
//...do something with pos.
}
var pos = //...something;
navigator.geolocation.getCurrentPosition(success(pos));
I just don't understand what is going on here. Where does the argument come from and why isn't the function even invoked with parentheses?
This is a feature you will see often in Javascript. It is commonly called a callback. The lack of parentheses is because Javascript allows you to treat a function like a variable, often referred to as 'first-class functions'. You are passing the success function to the getCurrentPosition method, you are not actually calling the success method.
When you call navigator.geolocation.getCurrentPosition(success);, you are saying to the getCurrentPosition function that when it has found the position, you would like it to call the function you have provided and pass it the position it got.
The getCurrentPosition method will be doing something like the following:
function getCurrentPosition(successCallback) {
var position = loadFromSomewhereThatMayTakeAWhile();
successCallback(position);
}
getCurrentPosition may take many seconds or even minutes to get the current location. You do not want the browser to stop responding while this is happening. Callbacks allow you to say "when this operation has finished, call this other method to do something with the result". The browser can then carry on with other things and only execute your callback when the operation is complete.
The jQuery ajax function uses this callback style.
var whenSuccessful = function(data, status, xhr){
console.log('The data was loaded successfully.')
};
var whenFailed = function(xhr, status, error){
console.log('The request failed!')
};
$.ajax({
url: "http://myserver.com/some_data.json",
error: whenFailed, // do this if the request fails for any reason
success: whenSuccessful // do this if the data was loaded successfully
})
Related
I ask a friend and ask what is (data, function(i,e) in this code and he said this is callback then i search the internet about callback and doesn't understand it. I read about this What are callback methods?what is callback in simpliest way ?
$.each(data, function(i,e){
console.log(e.id);
});
What is the use of (data, function(i,e) here?
$.ajax({
type: "GET",
url: pbxApi+"/confbridge_participants/conference_participants.json?cid="+circle,
dataType: "jsonp",
jsonpCallback: 'callback',
contentType: "application/javascript",
success: function(data) {
console.log(data);
}
});
A callback function is a function you specify to an existing function/method, to be invoked when an action is completed, requires additional processing, etc.
*Here's a little something for you to understand callbacks better:
Guy 1 to Guy 2: hey dude I wanna do something when a user clicks in there, call me back when that happens alright?
Guy 2 calls back Guy 1 when a user clicks here.*
A callback method which is called back.
Who calls it back at you ?
Your framework calls it back.
Why it calls it back ?
Because you ask for it to get called back because you want to do some processing when something happens.
Examples
You are doing some processing and don't know when it completes. You provide a callback , and you continue with some other work. Your call-back function will be called back to tell you that processing is finished and you can do something at your end now.
You want to know when some control fires some event so that you can do some processing. You provide a call-back function as event handler.
You are not happy with default processing done by framework and want to override that processing, you provide a call-back and framework calls it back to use your own processing.
So, in general : You ask a component/framework to call your provided method. You never call that provided method from your code, someone else calls it back.
A callback function is a function that is passed to another function as a parameter, and the callback function is called (or executed) inside the another Function.
Like this
(data, function(i,e)
We can pass functions around like variables and return them in functions and use them in other functions. When we pass a callback function as an argument to another function, we are only passing the function definition.
Note that the callback function is not executed immediately. It is “called back” at some specified point inside the containing function’s body. For more info Refer Here
Normally, JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.
To prevent this, you can create a callback function.
A callback function is executed after the current effect is finished.
For e.g, this is a call back function:
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
In this case the function hide will be executed before that alert which is precisely what we want.
On the other hand if you don't use call back function say this way:
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
In this case alert will be executed even before the function hide is executed. This is the typical use of callback function in Javascript.
Whenever I try to find answer of this question everyone refers to ajax start/stop etc.
I am using XUI JS's XHR function for cross domain calling, now I want exactly like this
callMyXHRfunction();
callNextFunctionWhenAboveFunctionResponded();
i.e. I should move forward until unless my xhr function responds (either success or failure)
Update
Use Case:
There is a function called getAllData(), this function get all my current data submitted to server. I need to call this function often to get the latest data and move ahead. While loggin I call this function to get latest data and after every 10 mins I need to call this to get data refreshed.
So if I call each my function on success function then my code may confuse other developer and if I write like above he/she will easily know what is going on in first line and in 2nd line.
Hope now everyone understand my situation very well.
See third example on the website you are referencing:
x$( selector ).xhr( url, fn );
Second argument can be a callback, callback being the keyword you were probably looking for to begin with.
Alternatively, use a synchronous call by supplying async: false as an option.
x$("body").xhr("http://the-url",{ async: false });
Control flow will pause until the request returned and only then continue with your next function. See http://jsfiddle.net/ZQ9uw/ for reference.
You need to make the .xhr call in a way that specifies a callback function and pass in your "next" function as the callback.
So you'd write it like this:
callMyXHRFunction(nextFunctionToCall); // no parens after nextFunctionToCall!
function callMyXHRFunction(callback) {
$("something").xhr(url, {
error: callback, // so that nextFunctionToCall is called on error
callback: callback, // so that nextFunctionToCall is called on success
async: true
// add more options here
});
}
It's probably obvious to you, but I can't figure it out.
I need to make function that returns it's inner-function's value. In other words, I have function get_users() that must return JSON object. That JSON object is got by $.post (built-in jQuery).
function get_users() {
return
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
return response;
},
'json'
);
}
(above is what I tried to do, but it returned undefined - what a surprise)
Because of variable scope, I cannot just make variable in inner-function because it won't be visible in main function. I don't want to use global variables neither. Looking for better solution!
Thanks in any advice!
Why are you fighting against the asynchronous nature of AJAX? When you do AJAX you should get accustomed to work with events and callbacks instead of writing sequential code. You can't return the inner contents. The simple reason for this is that this inner function could execute much later than the outer function. So the outer function will return a result much before the success callback executes.
So here's the correct way:
function get_users() {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// instead of trying to return anything here
// simply do something with the response
// Depending on what the server sent you there
// will be different ways.
// Here you could also call some other custom function
// and pass it the response
}
'json'
);
}
You can't return values from ajax calls. (Without setting async false, but that wouldn't really be ajax)
By the time you hit the inner return, the outer function has already completed
You will need to use a callback to process the users.
get_users(function(response) { // this anonymous function is passed in as a parameter
// do something with the response
});
function get_users(callback) {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// call the passed in function and pass in the response as a parameter
callback(response);
},
json'
);
}
You need a primer on how asynchronous ajax calls work.
When you call $.post(), it starts a networking call to do the post and immediately returns from the $.post() call and continues executing the rest of your javascript. It will even exit your function get_users() right away.
But, the ajax call is not yet done - it's still in progress. Some time later, the ajax call will finish and when that happens the success handler for the ajax call that you have defined as function(response) {...} will get called. Only then, at that later time, is the response value from the ajax call known.
This is what asynchronous ajax means. You cannot write a call like get_users() and expect it to get the users and return with them. Instead, you have to make use of callback functions that will get called some time later (when the ajax has completed) and you can continue the path of your code then. Yes, this is inconvenient, but it's how things work in javascript with asynchronous ajax calls. The benefit of asynchronous ajax calls is that the browser and other javascript code can be fully live while the ajax call is underway. The cost of asynchronous ajax calls is that coding for them is more complicated.
You have a number of choices for how to deal with this complication. First off, you can make your get_users() call and then just continue the programming sequence that you want to carry out in the internal callback inside of get_users() since that's the only place that the response (the actual users) is known. If you're only using get_users() in one place in your code, then that could work fine. It would look like this:
function get_users() {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// process the user list here and continue whatever other code you
// need that deals with the user list
},
'json'
);
}
If you need to use get_users() in several different places for different purposes, then you can change it to take a callback itself and let the post call just call that callback when the ajax call is done. You would then complete your processing of the response in that callback function:
function get_users(callback) {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
callback,
'json'
);
}
In this second option you could call get_users() like this:
get_users(function(response) {
// process the user list here and continue whatever other code you
// need that deals with the user list
});
There are even more advanced options available using jQuery's deferred object.
I'm trying to send a request and then in callback function, change the parameters and then send the request again. Something like this:
function sendRequest() {
params = {param1:'value', param2:'value'};
while(params) {
$.getJSON("url", params, function(data) {
if(data contains something important)
params.foo = bar;
else
params = null;
});
}
}
But params never changes and the while loop continues for ever. It seems to be a reference problem; but I can't figure out how to solve this. Thanks in advance.
The problem is that getJSON is asynchronous.
while(params) executes. It's truthy, so we continue
$.getJSON is called. The function passed to it will not be called at this time. It's just queued to the subsystem that later will perform the actual request - asynchronously.
while(params) executes again. The callback passed to getJSON has not gotten a chance to run yet, so params is unchanged.
Go to step 2.
In other words, you created an infinite loop, since the system that processes the queued callback function never gets to execute because of the infinite loop. All you end up doing is creating a infinitely long list of queued getJSON calls.
A better solution would be something like this:
function sendRequest(params) {
$.getJSON("url", params, function(data) {
if(data contains something important)
params.foo = bar;
sendRequest(params);
else
params = null;
// Probably do something like requestChainFinished(params);
});
}
sendRequest({param1:'value', param2:'value'});
By using a function, you take control of the flow and don't perform another request until the asynchronous callback to getJSON has been called.
'params' is a closure variable. The value of params changes at a later time in the callback when the asynchronous ajax call's response arrives, but your while loop is keeping the JS engine busy that the callback isn't going to get called ever.
Either you could keep calling the same function in the response callback or you can use async: false like this $.ajax({ async: false, ...
I have written a function that retrieves a html template, then binds data using jQuery.tmpl. I think it's fairly neat and tidy and encapsulates what I need and provides me a reusable function. My question however is can it be improved.
My main concern is what if the $.get method fails, and also how the callBack function is executed.
function Bind(templateURL, templateData, templateTarget, callBack){
var req = $.get(templateURL);
req.success(function(templateHtml) {
$(templateTarget).html(''); //clear
$(templateHtml).tmpl(templateData).appendTo(templateTarget); //add deal
callBack();
});
}
You can pass the result of tmpl() directly to html() to clear your target container and append the new content at the same time. You can also chain the result of $.get() into your success handler to avoid using a local variable:
function Bind(templateURL, templateData, templateTarget, callBack)
{
$.get(templateURL).success(function(templateHtml) {
$(templateTarget).html($(templateHtml).tmpl(templateData));
callBack();
});
}
If $.get() fails, nothing will happen since you do not register an error handler. What that handler would do is up to you, but you might want to display an appropriate message in an alert box or somewhere on the page.
Your second concern is less clear. As it stands, callBack will only be called on success, and without arguments.
You can use $.ajax to assign and error calback. ex:
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })
.error(function() { alert("error"); })
Check the api http://api.jquery.com/jQuery.ajax/