Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

Friday, January 3, 2014

JQuery "this" object has different meaning inside ajax call

Usual cases:
Most of the time we are using "$(this)" inside more events, by default "this" represent the current element's object.

For example:
If we need to delete a button, which having id "del", then we write a code as,
$('#del').click(function(){
         $(this).remove(); // Using "this" object to access current selected element.
});


In side an ajax call:
But inside the JQuery ajax call we could not use "this" object. Because ajax function already having a object called "this", which had different meaning. So we have to assign our "this" object into other name, before we going to use ajax.

For example:
Say same as above, we need to delete a button which having id "del", when it was clicked. But now we need to also perform a another action using ajax function. Action may anything like delete a post from database using back end codes like PHP.

So, we have code like follows,
$('#del').click(function(){
         var self=this; // Assigning "this" object into an other variable.
         $.ajax(function(){
                   url: 'delete_post.php',
   type:'POST',
   success:function(data){
                         $(self).remove(); // Using new variable "self" to access current selected element.
                  }
         });
});

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...