Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery and data-attributes to handle all ajax calls?

I'm thinking of a way to reduce the amount of javascript code by enabling ajax on links from attributes. Example:

<a href="/Default/Link.html" data-endpoint="/Ajax/Link.html" rel="targetId" async="true">Click me!</a>

async="true" will disable default behaviour of the link (href), and do a ajax call using the data-endpoint value and insert it to the element id defined in rel.

I'm no JS expert, so I'd appreciate any thoughts or pitfalls using this approach. Options like cache: true etc would be cool to be able to pass in as well, but not really needed as I'd like to do this to get partial views that contains more or less live data ( no cache needed).

(This is inspired from a talk i saw on how facebook minimized their code, but probably very simplified compared to how they optimize everything down to every bit 'n byte)

like image 374
olemarius Avatar asked Aug 02 '11 07:08

olemarius


People also ask

What are required attributes for AJAX call?

The parameters specifies one or more name/value pairs for the AJAX request. The data type expected of the server response. A function to run if the request fails. A Boolean value specifying whether a request is only successful if the response has changed since the last request.

What is data attribute in AJAX?

The data-* attribute gives us the ability to embed custom data attributes on all HTML elements. The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

Can jQuery and AJAX be used together?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!


1 Answers

Something like this

Html

<a href="/Default/Link.html" 
    data-endpoint="/Ajax/Link.html" 
    data-target="targetId" 
    data-cache="false",
    data-async="true">Click me!</a>

jQuery

$('a[data-async="true"]').click(function(e){
    e.preventDefault();
    var self = $(this),
        url = self.data('endpoint'),
        target = self.data('target'),
        cache = self.data('cache');

    $.ajax({
        url: url,
        cache : cache,
        success: function(data){ 
                       if (target !== 'undefined'){
                          $('#'+target).html( data );
                       }
                 }
    });
});
like image 115
Gabriele Petrioli Avatar answered Oct 02 '22 00:10

Gabriele Petrioli