开发者

ajax calls being called too fast

I have a page with a link, that the user clicks to log our api out of Facebook. When you click on it, it calls a ajax function that calls a php method to delete the users keys from our database, then calls the Facebook api logout function from a JS command. This calls Facebook and ends the users session. Once logged out, it refreshes the page.

My issue is that it seems to be not waiting for the database update to finish and logouts of Facebook and refreshes the page. Since it doesn't finish it, the info is never deleted and my site never logs out. Every once in a while, it does wok, but maybe once every 10 clicks.

I put in a开发者_StackOverflow setTimeout for 2 secs, but it still didn't work.

Any ideas?


Don't use setTimeout to try to time a follow-up action to an Ajax call. Use a callback function instead; that way it is guaranteed to only execute after the Ajax call is finished.


As per the comments, I see that you're using jQuery. In this case you just need to pass-in a callback function as function argument. Also see the jQuery.get documentation.

$.get('foo.php', function() {
    alert('Finished!');
});

or

$.get('foo.php', functionname);

// ...

function functionname() {
    alert('Finished!');
}

To learn more about jQuery I strongly recommend to learn how to find/read/interpret their online documentation. It's really excellent. There's also a Tutorials section at the home page. jQuery is not just JavaScript. It's a JavaScript based library.


Are you waiting for the AJAX callback? Since it's an asynchronous request, you aren't guaranteed that it's finished until it calls the onreadystatechange() function with status=4.

EDIT: An example of what I'm talking about:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.responseText == 'logged out successfully') {
    facebookLogout(uid);
  }
}
xhr.open('GET', 'http://example.com/my_logout.php?uid=' + uid, true);
xhr.send();

EDIT 2: To clarify your questions in the comments:

1) Yeah, PHP would just has to do an echo. It's not necessary - I just added that as an example to make sure the request finished not because it failed/got aborted.

2) As for $.get and friends, that's jQuery rather than pure Javascript, which has its own tools. In jQuery you'd write something like:

$.get('my_logout.php?uid=' + uid, function(data) {
   if (data == 'logged out successfully') {
     facebookLogout(uid);
   }
 });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜