views:

72

answers:

2

Hello,

I want to display a success msg after finishing an Ajax call. I tried to do the following:

$("form.stock").submit(function(){
   $.post('/ajax/transactionupdate', params, function(data) {
     $this.append("success");
   }
});

The problem is that inside the callback function, it seems like $(this) is unknown (not part of the instance).

So I tried to use ajaxComplete / ajaxSuccess as follows but for some reason they are not even initiated once the ajax is finished:

 $(this).ajaxComplete(function() {
        alert("STOP");
  });

However, the ajaxStart does seem to work:

  $(this).ajaxStart(function() {
        alert("START");
  });

Can anyone notice whats the problem?

Thanks! Joel

A: 
$("form.stock").submit(function(e){
   e.preventDefault()
   var el = this;
   $.post('/ajax/transactionupdate', params, function(data) {
     $(el).append("success");
   }
});

The context is the window since the XMLHttpRequest method is owned by window and that internally is invoked by $.post.

meder
Great!! It works, thank you very much
Joel
A: 

First, that initial example could be re-done like this:

$("form.stock").submit(function() {
  var stockForm = $(this);
  $.post('/ajax/transactionupdate', params, function(data) {
   stockForm.append("success");
  });
  return false;
});

You should return false from the "submit" handler to prevent the "native" form submit from happening.

Pointy
Also working, thanks for the info about the "native" submittion
Joel
Returning `false` and calling that "preventDefault()" routine on the event object will have the same effect for you. (Actually returning `false` will also have the effect of calling "stopPropagation", which for a form "submit()" routine isn't super-interesting because you'd rarely have nested forms.)
Pointy