tags:

views:

8571

answers:

2

how do i define the success and failure function of an ajax $.post?

+5  A: 

The documentation is here: http://docs.jquery.com/Ajax/jQuery.ajax

But, to summarize, the ajax call takes a bunch of options. the ones you are looking for are error and success.

You would call it like this:

$.ajax({
  url: 'mypage.html',
  success: function(){
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});

I have shown the success and error function taking no arguments, but they can receive arguments.

The error function can take three arguments: XMLHttpRequest, textStatus, and errorThrown.

The success function can take two arguments: data and textStatus. The page you requested will be in the data argument.

Jere.Jones
+6  A: 

If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.

Instead of this:

$.post("/post/url.php", parameters, successFunction);

you would use this:

$.ajax({
    url: "/post/url.php",
    type: "POST",
    data: parameters,
    success: successFunction,
    error: errorFunction
});

There are lots of other options available too. The documentation lists all the options available.

Matthew Crumley
@Matthew: is there anything specific that is checked on the server side, during the url.php call? as in how would i know if the call was successful or erroneous? do i have to return true/false, null or something of the sorts? I'm trying this on struts, and a little confused what my action class should return. As in how would i know something went through successfully or didn't..
Kaushik Gopal
@Kaushik: It's based on the HTTP status code returned by the server. Basically, anything except 2xx or 304 (not modified) is considered an error. The other conditions are if the connection times out or you can't connect to the server for some reason.
Matthew Crumley
@Matthew Perfect! that makes sense. Cheers.
Kaushik Gopal