Search code examples
cssajaxjqueryxmlhttprequestcss-selectors

Auto ajax selectors with Jquery


I'm trying to make a proof of concept website, but I want perfect degradation. As such I'm going to code the website in plain XHTML first and then add classes & ids to hook them in jQuery.

One thing I want to do is eventually enable Ajax xmlhttprequest for all my links, so they display in a viewport div. I want this viewport to be a "universal" dump for any xmlhttprequest from multiple external pages.

I was wondering if I'm able to hardcode something like:

<a href="blah.html" class="ajax">, <a href="bleat.html" class="ajax">

etc. So as you can see, I give all link tags that I want to call Ajax requests from with the class ajax. In my JS based on jQuery, I want to be able to code it such that all positive ${"a").filter(".ajax") will automatically load their respective hrefs [variable] as a ajax request.

Please help. I'm a n00b.


Solution

  • With your example, you should be able to do:

    $('.ajax').click(function () { 
        // Your code here. You should be able to get the href variable and
        // do your ajax request based on it. Something like:
        var url = $(this).attr('href');
        $.ajax({
            type: "GET",
            url: url
        });
        return false; // You need to return false so the link
                      // doesn't actually fire.
    });
    

    I would suggest using a class different from "ajax" because it makes the code a little strange to read, because $('.ajax') could be misread as $.ajax().

    The $('.ajax').click() part registers an onClick event handler for every element on the page with the class "ajax" which is exactly what you want. Then you use $(this).attr('href') to get the href of the particular link clicked and then do whatever you need!