I have the following code:
<div id="parentDiv">
<a href="someurl"> ... </a>
</div>
HTML inside the div comes from the external source and I don’t know it’s structure and can’t control it.
I need to post some data when this link has been clicked. So I added an onclick event handler on the div element, hoping event will propagate, and posted data with jQuery ajax function.
This worked fine in all browsers but Safari – it doesn’t return any errors, calls the callback function but doesn’t reach the server for some reason. I write to database every time I get a request. Tried to manually load the post url in browser – works fine and record in db is created. Also tried FF and Chrome – works as expected.
When put an alert into callback function it’s being called but in Safari data = null.
$('#parentDiv').delegate( 'a', 'click', function()
{
$.post('posturl',
{ param1: 'test'},
function(data)
{
alert('data = '+data);
},
"json"
);
});
Is it correct to expect AJAX working in this situation at all? And is there a better solution to this problem?
Thank you!
This sounds like you need to combine
delegatewith the asynchronous AJAX. Note that this is almost never a good thing — the only real exception is when you want to do an AJAX request immediately before leaving a page.Your code might look something like this:
This waits for the POST request to finish before continuing to follow the link. Note that this is superior to using
location = urlin a success callback as this solution allows normal browser action like middle-clicking to be followed as normal.