aroos
aroos

Reputation: 505

reusable JQuery ajax GET by passing a variable

From the browser, when a user clicks a button or link (out of a large list A to ZZZ), I'm trying to GET an HTML fragment (predefined) back from the server.

1) Whats the most reusable way to perform AJAX GET's instead of coding them all over the place.

The list of buttons could grow sequentially.

Upvotes: 0

Views: 59

Answers (1)

shenku
shenku

Reputation: 12458

The way that I would do it personally is to use the JQueryUi Widgets.

You could then do something fabulous like this - of course there are a million variations so use this as an idea and modify it to suit.

<div id="TargetElement">Empty</div>

<button role="reloader" data-get-url="http://www.google.com" data-get-target-id="#TragetElement">A special button or link.</button>

Then the widget:

$.widget( "custom.reloader", {

      _create: function() {

        var element = $(this);

          element.click(function(e){
             e.preventDefault();

             var getUrl = element.data('get-url');
             var target = element.data('get-target-id')

             $.get( getUrl, function( data ) {
              $(target).html( data ); 
            });

          });
      },

    });

And just call $('[role=reloader]').reloader(); in onload or something to apply to all buttons of that role

:D

(not tested, but should work)

Upvotes: 1

Related Questions