PHP Developer / Blog

February
15th, 2008

Solving “connection failure” for YUI’s asyncRequest

Digg this article · Save to del.icio.us · Stumble it!

Earlier today I was receiving a failure response when using YUI’s YAHOO.util.Connection.asyncRequest method to make an ajax call. The YUI documentation on this doesn’t help too much when troubleshooting the problem so we need to figure out what the heck is going on.

The cause
Context is very important for this problem. I was experiencing this while using a dHTML dialog which issued the asyncRequest call. Immediately after issuing the asyncRequest call I closed the dialog…and the request along with it. The dialog I was using wasn’t under my control and so I could not easily change the behavior of the dHTML dialog closing.

The solution
Since the request isn’t instantaneous we want to make the asyncRequest call and have it run outside the dialog itself. This will help ensure that the process runs until it has time to get a response back from the server. A quick way to do this is to define a function which executes the asyncRequest in the main document and execute it as a process within the window object. This can easily be done using window.setTimeout(”myAsyncFunction()”, 0). I haven’t tested this but the same should apply if you’re using popups. For popups opener.setTimeout(”myAsyncFunction()”, 0) should work. We can use a value of 0 since we are only worried about where the process runs…not when. Just make sure that myAsyncFunction is defined in the main window. The full code might look something like this.

var myAsyncFunction = function()
                      {
                        YAHOO.util.Connect.asyncRequest('GET', '/',
                          {
                            failure: function(o){ console.info(o.statusText)},
                            success: function(o){ console.info("YAY!")},
                          });
                      }
[...]
// in your dhtml closing dialog code
window.setTimeout("myAsyncFunction()",0);
[...]
// in your popup closing dialog code
opener.setTimeout("myAsyncFunction()",0);

I’m new to YUI and didn’t find anything similar to prototype.js’ bind method. That would be a more ideal solution so if you’re know how to do that with YUI…leave a comment.

Leave a Reply

Captcha
Enter the letters you see above.


About this site:
This is my (Jaisen Mathai) personal site for potential employers who want to see my resume or portfolio. My ideal job would be to work as a PHP developer on a large scale consumer website. My experience is in using PHP, MySQL, Ajax and JSON. I really enjoy creative brainstorming...taking a problem apart and narrowing 100 solutions down to the best one.

Thanks for stopping by. Be sure to drop me a line.