natasha
natasha

Reputation:

Catching server side errors inside Ajax form submission

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

Upvotes: 0

Views: 475

Answers (3)

Tangi
Tangi

Reputation: 33

This is an example done in php. Hope it is useful.

<html><!-- This is index.php -->
    <head>
        <script src="js/jquery.js" type="text/javascript"></script><!-- link to jQuery -->
        <script language="javascript"> 
        $(document).ready(function () {
            $('input#send').click(function(){
                /* Empty div#error and div#result incase they contain info from the last submission */
                $('#error').empty('');
                $('#result').empty('');
                /* Client-side validation */
                var name = $("input#name").val();
                var age = $("input#age").val();
                if (name==''){
                    alert('Insert your name.');
                }
                else if (age==''){
                    alert('Insert your age.');
                } else { 
                    var params = 'name=' + name + '&age=' + age;   
                    $.ajax({        
                         url:'b.php',        
                         type:'post',                 
                         dataType:'html',            
                         data:params,
                         cache: false,            
                         success:data     
                         }); 
                    function data (html) {
                        var $html = $( html ); // create DOM elements in a jQuery object
                        /* Return errors from 'b.php' */
                        $html.filter('#err').appendTo("#error");
                        /* Return valid Post */
                        $html.filter('#res').appendTo("#result");
                        /* Clear name input */
                        $('input#name').val('');
                        /* Clear age input */
                        $('input#age').val('');
                    }
                }
            }); 
        }); 
        </script>
        <style type='text/css'>
            #error{
                color:maroon;
                font-weight:bold;
            }
            #result{
                color:green;
                font-weight:bold;
            }
        </style>
    </head>
    <body>
        <div id="error"></div><!-- View Errors -->
        <div id="result"></div><!-- View valid Post -->
        <input type='text' name='name' id="name" value='' /><br/ >
        <input type='text' name='age' id="age" value='' /><br/ >
        <input type='submit' name='send' id="send" value='Send' />
    </body>
</html>

<?php /* This is b.php */
if(($_POST['name']=='')||($_POST['age']=='')){
    $error = '<div id="err">Error: Fill in ALL fields.</div>';
} elseif(is_numeric($_POST['name'])){
    $error = '<div id="err">Error: Name should NOT contain numbers.</div>';
} elseif(!is_numeric($_POST['age'])){
    $error = '<div id="err">Error: Age should ONLY contain numbers.</div>';
} else{
    $result = '<div id="res">Hi '.$_POST['name'].', you are '.$_POST['age'].' years old.</div>';
}
echo $error;
echo $result;
?>

Upvotes: 1

Vinay Sajip
Vinay Sajip

Reputation: 99365

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.

Upvotes: 0

Josh Stodola
Josh Stodola

Reputation: 82483

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.

Upvotes: 0

Related Questions