tags:

views:

120

answers:

2

Hi,

I am working with a Java application, and I have ajax form submission from a modal window. I would like the code to load either success or error page in the modal depending on the server side processing results. The following code is working for the success scenario only.

            $.ajax({
                type: "POST",
                url: action,
                data: params,
                success: function() {
                    $("#p_content").load("/test.jsp?id=12345");
                }
            });

I am fairly new to ajax, but from what I understand it is not enough to add the "error:" portion to the script above, it will not detect errors in my servlet code. Is there any way I can read a request parameter from inside this function? Or perhaps I can use something else? Please help!

Thanks, natasha

A: 

Your servlet should return the appropriate HTTP status code when something unexpected occurs (usually 500). jQuery will invoke your error callback function when the server responds with a problematic status code.

Josh Stodola
I do not want to modify existing java code which is used elsewhere. The servlet sets the error message parameter and redirects back to error page, or redirects to success. I was hoping to retrieve the error message parameter and determine which html to load based on that value.
Well, you are going to have to modify it to make it work with AJAX. Bottom line. Now if you don't want to mess with anything that is already using it, have your ajax send it a special parameter (indicating it is an AJAX request), and change the servlet to look for this new parameter and react accordingly. If the new parameter is not there, have the servlet continue doing what it is doing now. AJAX is not just client-side code, you have to work on both ends of the wire to get things to play nicely.
Josh Stodola
A: 

If you cannot avoid sending an apparent HTTP success code (1xx, 2xx or 3xx) even when an error occurs server-side, then jQuery will always call your success function. You'll need to inspect the data sent back in you client-side (JS) code, to determine what you do with the returned information in the browser.

Vinay Sajip