submit the form using ajax

127,301

Solution 1

Nobody has actually given a pure javascript answer (as requested by OP), so here it is:

function postAsync(url2get, sendstr)    {
    var req;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        }
    if (req != undefined) {
        // req.overrideMimeType("application/json"); // if request result is JSON
        try {
            req.open("POST", url2get, false); // 3rd param is whether "async"
            }
        catch(err) {
            alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
            return false;
            }
        req.send(sendstr); // param string only used for POST

        if (req.readyState == 4) { // only if req is "loaded"
            if (req.status == 200)  // only if "OK"
                { return req.responseText ; }
            else    { return "XHR error: " + req.status +" "+req.statusText; }
            }
        }
    alert("req for getAsync is undefined");
}

var var_str = "var1=" + var1  + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
    // hint: encodeURIComponent()

if (ret.match(/^XHR error/)) {
    console.log(ret);
    return;
    }

In your case:

var var_str = "video_time=" + document.getElementById('video_time').value 
     + "&video_id=" + document.getElementById('video_id').value;

Solution 2

What about

$.ajax({
  type: 'POST',
  url: $("form").attr("action"),
  data: $("form").serialize(), 
  //or your custom data either as object {foo: "bar", ...} or foo=bar&...
  success: function(response) { ... },
});

Solution 3

You can catch form input values using FormData and send them by fetch

fetch(form.action,{method:'post', body: new FormData(form)});

function send(e,form) {
  fetch(form.action,{method:'post', body: new FormData(form)});

  console.log('We send post asynchronously (AJAX)');
  e.preventDefault();
}
<form method="POST" action="myapi/send" onsubmit="send(event,this)">
    <input hidden name="crsfToken" value="a1e24s1">
    <input name="email" value="[email protected]">
    <input name="phone" value="123-456-789">
    <input type="submit">    
</form>

Look on chrome console>network before 'submit'

Solution 4

You can add an onclick function to your submit button, but you won't be able to submit your function by pressing enter. For my part, I use this:

<form action="" method="post" onsubmit="your_ajax_function(); return false;">
    Your Name <br/>
    <input type="text" name="name" id="name" />
    <br/>
    <input type="submit" id="submit" value="Submit" />
</form>

Hope it helps.

Solution 5

Here is a universal solution that iterates through every field in form and creates the request string automatically. It is using new fetch API. Automatically reads form attributes: method and action and grabs all fields inside the form. Support single-dimension array fields, like emails[]. Could serve as universal solution to manage easily many (perhaps dynamic) forms with single source of truth - html.

document.querySelector('.ajax-form').addEventListener('submit', function(e) {
    e.preventDefault();
    let formData = new FormData(this);
    let parsedData = {};
    for(let name of formData) {
      if (typeof(parsedData[name[0]]) == "undefined") {
        let tempdata = formData.getAll(name[0]);
        if (tempdata.length > 1) {
          parsedData[name[0]] = tempdata;
        } else {
          parsedData[name[0]] = tempdata[0];
        }
      }
    }

    let options = {};
    switch (this.method.toLowerCase()) {
      case 'post':
        options.body = JSON.stringify(parsedData);
      case 'get':
        options.method = this.method;
        options.headers = {'Content-Type': 'application/json'};
      break;
    }

    fetch(this.action, options).then(r => r.json()).then(data => {
      console.log(data);
    });
});

<form method="POST" action="some/url">
    <input name="emails[]">
    <input name="emails[]">
    <input name="emails[]">
    <input name="name">
    <input name="phone">
</form>
Share:
127,301
Alessio Melani
Author by

Alessio Melani

Updated on July 19, 2022

Comments

  • Alessio Melani
    Alessio Melani almost 2 years

    I'm developing an application (a kind of social network for my university). I need to add a comment (insert a row in a specific database). To do this, I have a HTML form in my html page with various fields. At time of submit I don't use the action of form but i use a custom javascript function to elaborate some data before submitting form.

    function sendMyComment() {
    
        var oForm = document.forms['addComment'];
        var input_video_id = document.createElement("input");
        var input_video_time = document.createElement("input");
    
        input_video_id.setAttribute("type", "hidden");
        input_video_id.setAttribute("name", "video_id");
        input_video_id.setAttribute("id", "video_id");
        input_video_id.setAttribute("value", document.getElementById('video_id').innerHTML);
    
        input_video_time.setAttribute("type", "hidden");
        input_video_time.setAttribute("name", "video_time");
        input_video_time.setAttribute("id", "video_time");
        input_video_time.setAttribute("value", document.getElementById('time').innerHTML);
    
        oForm.appendChild(input_video_id);
        oForm.appendChild(input_video_time);
    
        document.forms['addComment'].submit();
    }
    

    The last line submits the form to the correct page. It works fine. But I'd like to use ajax for submitting the form and I have no idea how to do this because I have no idea how to catch the form input values. anyone can help me?