views:

78

answers:

5

I am doing an ajax post in my code like this,

$.post("myAction",$("#myForm").serialize(), 
        function(response) {alert(response);});

if my response is an error message from my controller, I would like to display it not in an alert box, but in a regular browser page. How can I do this?

Thanks.

+4  A: 

You could redirect to an error page based on the response, something like:

$.post("myAction",$("#myForm").serialize(), 
        function(response) {
            alert(response);
            if(response == 'Error') {
                window.location.href = '/MyErrorPage.html';
            }

});

Or you could replace the contents of the current page with the response, e.g.:

$('body').html(response);
karim79
A: 

You could probably try to attach a callback to the ajaxError-event handler:

$.ajaxError(
  function (event, XMLHttpRequest, ajaxOptions, thrownError) {
    window.location = '/error.html'
});
PatrikAkerstrand
N.B this requires the OP to ensure an error response code is returned rather than just a html fragment. The ajax error will not fire unless it has a failure response code.
redsquare
+4  A: 

It's better to use the $.ajax method because you can handle the error messages in a better way (like, if the server returns a 404 error or something like that). You could use that way:

$.ajax({
    type: "POST",
    url: "page.php",
    dataType: "text",
    success: function(xhr) {
     if(xhr == 'error') {
      window.location.href = '/MyErrorPage.html';
     }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
     window.location.href = '/MyErrorPage.html';
    }
});
Willy Barro
I like more to use ajax() instead of post(), but technically his ajax request doesn't have an error, and is a valid from ajax point of view. Is just a response that can be interpreted as an error.
Elzo Valugi
A: 

Aside from the advise given above, you can use the Jquery Form Plugin which will take care of all your ajax form needs.

url: http://malsup.com/jquery/form/

Rishav Rastogi
+1  A: 

If you're going to show the return value as is it might confuse users because they would expect things to be more deatiled than a simple 'error'.

I think Karim79 has a proper approach but it is too complex because you will have to design a complete new page just for error handling.

I would recommend that you set up your own error-handling function in the page itself and based on the response show a human-readable message.

It could look something like this

$.post("myAction",$("#myForm").serialize(), 
        function(response) {
            alert(response);
            if(response == 'Error') {
                $('#errorMsg").html("Could not get results from server. Please try again later.");
            }

});
Cyril Gupta