While working on a website I had a content area division whose content I wanted to update according to the image I click on. Now, I had a customized scrollbar which I used in the content area. Now at first I wrote the following snippet for onclick script function :
function xyz(){
$("#content-area").load("abc.php");
$("#content-area").mCustomScrollbar({scrollButtons:{enable:true}});
}
But the second line of the script wasn't responding i.e, I wasnt getting the scrollbar. Instead when I used this piece of code snippet it worked :
$.post("abc.php", function(data){
$("#content-area").html(data);
$("#content-area").mCustomScrollbar({scrollButtons:{enable:true}});
});
I am wondering the function of the $.post() and why the first snippet didnt work while the second snippet worked?
In the first case that mCustomScrollbar
will be executed right after the AJAX request is sent: remember, first A
in AJAX is for asynchronous
. But it obviously has nothing to work on yet, as response from server is not here yet.
In the second snippet mCustomScrollbar
widget creation happens right after the AJAX request's response is received (as this line is part of $.post
success handler now) and that #content-area
is filled with necessary structure (with .html()
) call. So now it works correctly.
You can use the fact that $.load
method can be supplied with custom callback function that will be executed when the request completes, as described here. For example:
$("#content-area").load("abc.php", function() {
$(this).mCustomScrollbar({scrollButtons:{enable:true}});
});
Note $(this)
usage: as this
is set to each DOM element in turn inside that callback function, you don't need to walk over the DOM looking for that content-area
yet again; it's enough just to wrap that element into jQuery object.
I suppose that in the first example the second statement was being executed before the completion of the .load()
function. In the second you are correctly using the success function, which is only executed after the completion of the POST request.
You need to use callback function which is executed when request is complete:
$("#content-area").load("abc.php", function(){
$(this).mCustomScrollbar({scrollButtons:{enable:true}});
});