javascript - How to submit form without reloading page, without jQuery? - Stack Overflow

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

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); 
}

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); 
}
Share Improve this question edited Jun 19, 2017 at 14:50 Markus L 1,0142 gold badges22 silver badges40 bronze badges asked Jun 28, 2016 at 5:36 newbieprogrammernewbieprogrammer 8787 gold badges26 silver badges47 bronze badges 3
  • 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 Commented Jun 28, 2016 at 5:38
  • 1 Possible duplicate of Submit form without reloading page – Abhishek Commented Jun 28, 2016 at 6:02
  • Does this answer your question? Submit form without page reloading – SuperStormer Commented Oct 1, 2022 at 2:35
Add a ment  | 

3 Answers 3

Reset to default 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;"
>

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

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 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1740935641a4277835.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信