Theming

Implementing AJAX with jQuery

Last updated March 2, 2020
Categories

Check your version

This tutorial covers a topic in which may or may not be the version you're using. We're keeping this tutorial online as a courtesy to users of , but we consider it archived.

Alternate resources

Sprout Video

AJAX is one of the main reasons to use a Javascript library such as jQuery. See how simple it is to perform a previously difficult task that required complex browser specific code to preform reliably and was prone to simple mistakes. Implement basic AJAX requests using jQuery's built in methods which make it extremely simple to send an asynchronous request to a server, gather the returned data, and insert it into the page.

Example code:


// AJAX Live Function
$('.content p').live('mouseenter mouseleave',
  function() {
    $(this).toggleClass('hilight');
  }
);

// AJAX Example
$('.node_read_more a').click(function() {
  var url = $(this).attr('href');
  var link = this;

  $.ajax({
    url: url,
    success: function(data) {
      var $fullContent = $('#content-output .content', data);
      var html = $fullContent.html();
      $(link).closest('div.node').find('div.content').html(html);
      $(link).hide();
    }
  });
  return false;
});