Ajax script not working properly how to know call to servlet is made by ajax

I have started AJAX with servlets but my first program is not working. Here is the code:

<form action="./ajax" method="get" id="myAjaxRequestForm">
    <input type="text" name="name" id="name" />
    <input type="text" name="email" id="email" />
    <textarea rows="5" cols="20" name="address" id="address"></textarea>
    <input type="submit" id="myButton" value="Register" />
</form>
$(document).ready(function(){
    $('#myButton').click(function(event){
        alert();
        var name = $('#name').val();
        var name = $('#email').val();
        var name = $('#address').val();
        $.ajax({
            type:   "GET",
            url:    'ajax',
            data:   "name = " +name+ "&email="+email+"&address"+address,
            success: function(msg){ 
                alert("Success");
            },
            error: function(e){
                alert("Error");
            }
            event.preventDefault();
        });
    });
});
public class ajax extends HttpServlet 
{
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 
    {       
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        String address = req.getParameter("address");
        System.out.println(name);
        System.out.println(email);
        System.out.println(address);
        PrintWriter p = res.getWriter();
        p.println("success");
    }
}

This program has to display a popup with the success or failure message but it redirects to a page with servlet message. It is not showing the popup. When using an XML file I have no issues.

Answers 1

  • You have several problems. Firstly you're assigning the value of all your inputs to the name variable instead of their own variables. The manual creation of those variables is redundant anyway as you can simply use the serialize() method on the form anyway.

    Secondly, the preventDefault() call should be within the anonymous function you provide to the click handler, not within the $.ajax settings object.

    Finally you should hook to the submit event of the form, not the click event of the submit button. Try this:

    $('#myAjaxRequestForm').submit(function(event) {
        event.preventDefault();
        $.ajax({
            type: "GET",
            url: 'ajax',
            data: $(this).serialize(),
            success: function(msg){ 
                console.log("Success");
                console.log(msg);
            },
            error: function(e){
                console.log("Error");
            }
        });
    });
    

    Final tip; always use console.log to debug. alert() coerces all types to string, so you may not be seeing the correct data.


Related Articles