Sign in to follow this  
lopenka

[web] Ajax callback trouble

Recommended Posts

Hello, I have some problems with Ajax and javascript callbacks. My situation: I have N images on web site, each of them have asociated function that sends Ajax request on server. Each image send this request through same function, only url changes (different parameters, that stuff that goes after ?). When Ajax request is finished I want to update image that sent that request. Each image is upadated same way (for example, move it to the left i little). My problem: If user clicks on another image while previous Ajax request is being processed, new request is made and after first one is finished I do not know which image it belonged to. This could be easily solved if javascript callback could have parameters. I would sipmly set onreadystatechange to function with parameter that would contain ID of image that sent that request. I couldn't google any information about callbacks with parameters and I am beggining to think it is not possible in js. So first question is: Is it possible to set callback with parameter(s) to some event? Another solution I came up with is having some kind of queue that would store my parameters, on each request I would insert params to the end, on finished request I would take oldest param from that queue. For this to work, request would have to end in same order in which they started and I don't know if that is true. So my second question is: Does the Ajax requests end in same order they start in? If you have any other solution, please let me know

Share this post


Link to post
Share on other sites
Rather than do something like this:
{
var local; // Here's the local variable you want to access.
object.onevent = someFunction;
}

function someFunction() {
// Can't see local from here!
}



...try doing this:
{
var local;

object.onevent = function() {
// We can see local from here just fine.
};
}



Functions are first-class objects in javascript, which can be rather useful. [smile]

(EDIT: See below for proper terminology and an explanation!)

Share this post


Link to post
Share on other sites
You can use a closure for that. Remember how you can define one function inside the other? The inner function can still access the outer function's variables, so something like this should work:

function doAjaxStuffWithImage(imageId) {
...
// we instantiated our xmlHttpRequest object and now we'll set a callback
xmlHttpRequest.onreadystatechange = function() {
updateImage(imageId, xmlHttpRequest.responseText);
// see? the variables are still available here
}
}


EDIT: Scooped. Basically, what benryves said.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this