Simple jQuery Ajax Call on link onClick

For this code:

type: "POST",
url: "mysimplepage.php",
async: true,
data: { logDownload: true, file: $(this).attr("name") }
return false;

Why does the ajax call only work if I return false? If I return true the ajax call returns as an error. I would like the onclick to return true so that the link is followed.

Are you using an onclick=‘’ in the link too? Can you explain further and post your HTML?

You have bound a click event to an anchor tag which by default is designed to perform an action on the window to take you to another page, when you return false on the click it blocks that default action allowing the code inside the anonymous function to run without any issues. I don’t recommend you use return false; though as if something goes wrong with the Ajax code the default click action will still take effect causing unexpected behavior, instead what you would want to be using is the preventDefault method jQuery binds to the click event for cross browser support.

See the below example:

$('a').click(function(e) {
    // Normal code goes here but you no longer need return false;

Also if you’re using jQuery 1.5 and above its recommend you use the on and off methods as they have built in event delegation which allows for a nicer result instead of constantly binding events to new elements, see the below:

$('a').on('click', function(e) {

You can read more about the .on() method at the following link

1 Like