Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit form without reloading page, without jQuery?

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); 
}
like image 605
newbieprogrammer Avatar asked Jun 28 '16 05:06

newbieprogrammer


People also ask

How do I stop a page from refreshing in HTML?

Window stop() The stop() method stops window loading. The stop() method is the same as clicking stop in the browser.

How do you stay on the same page after submit in HTML?

You could include a hidden iframe on your page and set the target attribute of your form to point to that iframe. There are very few scenarios where I would choose this route. Generally handling it with javascript is better because, with javascript you can...


2 Answers

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;"
>
like image 130
Canu667 Avatar answered Oct 18 '22 19:10

Canu667


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

like image 45
Siddhartha Chowdhury Avatar answered Oct 18 '22 18:10

Siddhartha Chowdhury