submit the form using ajax

后端 未结 8 864
栀梦
栀梦 2020-12-05 10:17

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

相关标签:
8条回答
  • 2020-12-05 10:45

    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="a@b.com">
        <input name="phone" value="123-456-789">
        <input type="submit">    
    </form>
    
    Look on chrome console>network before 'submit'

    0 讨论(0)
  • 2020-12-05 10:46

    I would suggest to use jquery for this type of requirement . Give this a try

    <div id="commentList"></div>
    <div id="addCommentContainer">
        <p>Add a Comment</p> <br/> <br/>
        <form id="addCommentForm" method="post" action="">
            <div>
                Your Name <br/>
                <input type="text" name="name" id="name" />
    
    
                <br/> <br/>
                Comment Body <br/>
                <textarea name="body" id="body" cols="20" rows="5"></textarea>
    
                <input type="submit" id="submit" value="Submit" />
            </div>
        </form>
    </div>​
    
    $(document).ready(function(){
        /* The following code is executed once the DOM is loaded */
    
        /* This flag will prevent multiple comment submits: */
        var working = false;
        $("#submit").click(function(){
        $.ajax({
             type: 'POST',
             url: "mysubmitpage.php",
             data: $('#addCommentForm').serialize(), 
             success: function(response) {
                alert("Submitted comment"); 
                 $("#commentList").append("Name:" + $("#name").val() + "<br/>comment:" + $("#body").val());
             },
            error: function() {
                 //$("#commentList").append($("#name").val() + "<br/>" + $("#body").val());
                alert("There was an error submitting comment");
            }
         });
    });
    });​
    
    0 讨论(0)
  • 2020-12-05 10:48

    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) { ... },
    });
    
    0 讨论(0)
  • 2020-12-05 10:53

    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;
    
    0 讨论(0)
  • 2020-12-05 10:55

    I would like to add a new pure javascript way to do this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.

    const formInputs = oForm.getElementsByTagName("input");
    let formData = new FormData();
    for (let input of formInputs) {
        formData.append(input.name, input.value);
    }
    
    fetch(oForm.action,
        {
            method: oForm.method,
            body: formData
        })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.log(error.message))
        .finally(() => console.log("Done"));
    

    As you can see it is very clean and much less verbose to use than XMLHttpRequest.

    0 讨论(0)
  • 2020-12-05 10:56

    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>
    
    0 讨论(0)
提交回复
热议问题