RSS

Asynchronous AJAX and event propagation

03 Apr

Last night noticed interesting behavior in Safari. Imagine you have the following piece of HTML code:

<div id="holder">
    <a href="url"> ... </a>
</div>

And for some reasons (not important for this example) you want to catch link's onclick event on the <div> element instead of <a>, and then post some data with ajax before browser follows the link.

So you as me might have thought that the following javascript code would work just fine:

$("#holder").click(function(event) 
{
  	$.ajax({
      		url: "/clicked/",
      		type: "POST",
      		data: ({param1 : 'test'}),
      		dataType: "json",
      		async: true,
      		success: function(msg){ alert(msg); }
   	});
 });

And it does. But not in Safari. Interesting thing is that script doesn’t fail and it even shows an alert from “success” callback function. But “msg” returned is null.

First thing I thought was that browser got redirected before it reaches ajax code but it shows the alert so it’s not the case.

Then I tried preventing the event’s default behavior (following the link). Surprisingly it fixes the issue independently on when default is actually prevented – in the beginning of the function or after ajax call. For example:

$("#advert").click(function(event) 
{
  	event.preventDefault();
  	
    $.ajax({
      		url: "/clicked/",
      		type: "POST",
      		data: ({param1 : 'test'}),
      		dataType: "json",
      		async: true,
      		success: function(msg){ alert(msg); }
   	});

        // or call event.preventDefault(); here
 });

But this breaks the desired functionality – so not an option.

Then with help of lonesomeday from http://stackoverflow.com/ solution has been found! Turns out due to some internal optimisation (or something else Safari does behind the scenes) it doesn’t execute asynchronous requests at this point but does execute synchronous. So changing “async: true” to “async: false” fixes the issue. But it’s still remains a mystery why success callback was executed in the first place…

Advertisements
 
Leave a comment

Posted by on April 3, 2011 in JavaScript

 

Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: