8

I have form as follows, it require to sent an action to my java Servlet to do an update to the database.

How do I submit the form without the page get reloaded here? Currently with action="myServlet" it keep direct me to a new page. And if I remove the action to myServlet, the input is not added to my database.

<form name="detailsForm" method="post" action="myServlet" 
      onsubmit="return submitFormAjax()">
    name: <input type="text" name="name" id="name"/> <br/>
    <input type="submit" name="add" value="Add" />
</form>

In the view of my Java servlet, request.getParameter will look for the name and proceed to add it into my db.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
  throws ServletException, IOException
{   
    if (request.getParameter("add") != null) {
        try {
            Table.insert(name);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

In my JavaScript part, I have a submitFormAjax function

function submitFormAjax()
{
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for modern browsers
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
            alert(xmlhttp.responseText); // Here is the response
        }

    var id = document.getElementById("name").innerHTML;
    xmlhttp.open("POST","/myServlet",true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("name=" + name); 
}
Markus L
  • 932
  • 2
  • 20
  • 38
newbieprogrammer
  • 848
  • 7
  • 23
  • 46
  • You would need to return `false` from your function to stop the standard form submit from happening too. (And you would need to fix the syntax error in your function: the missing `"` before the closing `)` in `.getElementById("name)`.) – nnnnnn Jun 28 '16 at 05:38
  • 1
    Possible duplicate of [Submit form without reloading page](http://stackoverflow.com/questions/18169933/submit-form-without-reloading-page) – Abhishek Jun 28 '16 at 06:02
  • Does this answer your question? [Submit form without page reloading](https://stackoverflow.com/questions/2866063/submit-form-without-page-reloading) – SuperStormer Oct 01 '22 at 02:35

3 Answers3

6

A similar question was asked here Submit form without reloading page

Basically, do "return false" after invoking the function. Something like this should work:

<form name="detailsForm" 
      method="post" 
      action="myServlet" 
      onsubmit="submitFormAjax(); 
      return false;"
>
Canu667
  • 175
  • 1
  • 5
  • 2
    Yes - it did not work, because in the onsubmit handler we had 'return submitFormAjax(); return false;'. It should be 'submitFormAjax(); return false;'. I created a fiddle with it -> https://jsfiddle.net/yoL0f0mp/ - and edited and fixed the answer. – Canu667 Jun 20 '17 at 15:40
1

This is how I used to implement Ajax in JS without JQuery. As am a PHP and JS guy I cant possibly help you with Java Servlet side but yes heres my little help from JS side. This given example is a working example.See if it helps you.

// HTML side
<form name="detailsForm" method="post" onsubmit="OnSubmit(e)">


// THE JS
function _(x){
    return document.getElementById(x);
}

function ajaxObj( meth, url ) 
{   
    var x = false;
    if(window.XMLHttpRequest)
        x = new XMLHttpRequest();
    else if (window.ActiveXObject) 
        x = new ActiveXObject("Microsoft.XMLHTTP");  
    x.open( meth, url, true );
    x.setRequestHeader("Content-type", "application/json");
    return x;
}
function ajaxReturn(x){
    if(x.readyState == 4 && x.status == 200){
        return true;    
    }
}

function OnSubmit(e) // call this function on submit
{
    e.preventDefault();
    var username = _("name").value;        
    if (username == "") 
    {
        alert("Fill out the form first");
    }
    else
    {
            var all = {"username":username};
            all = JSON.stringify(all);
            var url = "Myservlet";

            var ajax = ajaxObj("POST", url);
              ajax.onreadystatechange = function()
              {
                if(ajaxReturn(ajax) == true)
                {
                   // The output text sent from your Java side in response
                   alert( ajax.responseText );
                }
              }
            //ajax.send("user="+username+");
            ajax.send(all);
    }
}

Thanks

Siddhartha Chowdhury
  • 2,724
  • 1
  • 28
  • 46
0

Change the code in form

onsubmit="submitFormAjax(event)"

Change your JS code

function submitFormAjax(e)
{
        e.preventDefault();
        var xmlhttp;
        if (window.XMLHttpRequest) {
        // code for modern browsers
        xmlhttp = new XMLHttpRequest();
        }
    ......
    ................
    ...............

return false;  //at last line 
intekhab
  • 1,566
  • 1
  • 13
  • 19