Alan Sutherland Alan Sutherland - 6 months ago 29
HTML Question

Refreshing one section of a page using Ajax context

I'm trying to refresh just one part of my page when a user clicks a 'clear' button, currently I'm using a bit of code I hacked off another answer I found on here:

$('.clear').click(function () {
$.ajax({
url: "",
context: document.body,
success: function (s, x) {
$(this).html(s);
}
});
});


This reloads the whole document body, how do I target a particular div or class?

context: document.body.somediv?

Answer

jQuery API about the context option:

This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example, specifying a DOM element as the context will make that the context for the complete callback of a request, like so:

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
});

So, the context option is to set the scope of the this object in the callback functions. By default it is the ajax object, with the current configuration:

$.ajax({
    url: ""
}).done(function(){
    console.log(this); 
    // logs: { url: "", type: "GET", etc... }
    // 
});

If you wish to target a specific section to load the response in, you can just use jQuery to find the element and put the response in that element, context is not relevant for you:

$.ajax({
  url: "",
}).success(function(data){
  // data is your response
  $(".some-element").html(data);
});

However, you can use context to make the configuration a bit easier to understand, like so:

$.ajax({
  url: "",
  context: $(".some-element")
}).success(function(data){
  $(this).html(data);
  // $(this) refers to the context object, in this case $(".some-element")
});

If you now want your ajax response to be loaded somewhere else on the page, you just have to change the selector on the context parameter.

Comments