SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    May 2008
    Location
    Missouri, USA
    Posts
    273
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Simple jQuery Ajax Call on link onClick

    For this code:
    Code:
    $('a').click(function(){
    $.ajax({
    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.
    Follow Me On Twitter: BryceRay

  2. #2
    SitePoint Zealot
    Join Date
    Nov 2001
    Location
    RI, USA
    Posts
    140
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Are you using an onclick='' in the link too? Can you explain further and post your HTML?
    in1.com | Bootply - Bootstrap playground

  3. #3
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,196
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    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:

    Code JavaScript:
    $('a').click(function(e) {
        e.preventDefault();
     
        // 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:

    Code JavaScript:
    $('a').on('click', function(e) {
        e.preventDefault();
    });

    You can read more about the .on() method at the following link http://api.jquery.com/on/


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •