0

Say I have a set-up like this:

$('#mylink').click(function(event){
   savePost();
});

<a id="mylink" href="http://google.com">my link</a>

If I click the link will I be gone to a different page without giving the function a chance to execute?

What if savePost() has ajax and a callback function? Will it execute regardless of what page the browser is on when the script executes? (or would I have to preventDefault on the link and put the window.location command within the callback)

3 Answers 3

2

Script will be executed first, then window.location

Sign up to request clarification or add additional context in comments.

Comments

1

Yes,

onclick script will be executed before changing window.location

on ajax callback, i don't think so, as ajax and callback are asynchronous calls,
so if you need to navigate only after success perform of ajax call use complete(jqXHR, textStatus) callback on jQuery.ajax() together with preventDefault()

see http://api.jquery.com/jQuery.ajax/

2 Comments

I don't have much experience with jQuery, but how about using jQuery.ajax( url, {async: false} ); ?
async: false is something you should never use, this is the rule.
1

Call event.preventDefault(); to prevent the link from actually changing the page. Otherwise the page will change after the onclick function has been executed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.