简体   繁体   中英

How Do I Post A Form Without Redirecting Using Raw Javascript?

I've seen several posts about how to post a form using AJAX, but I am curious about options for simplification.

Here's a trimmed down version of what I'm trying:

<form id="message-form" method="POST" action="/send-message" onsubmit="return false;">
    <input type="text" name="message"><br/>
    <input type="text" name="phone_number"><br/>
    <button type="button" onclick="return trysubmit()">Send Message</button>
</form>

<script>
    function trysubmit()
    {
        document.getElementById("message-form").submit();
        
        //notify user of success 

        //cancel the redirect
        return false; 
    }
</script>

In this case, the form gets submitted, but the redirect still happens.

Is something like the above even possible, or do I have to manually build an AJAX request like this? form serialize javascript (no framework)

var form = document.getElementById('message-form');
var data = new FormData(form);
var req = new XMLHttpRequest();
req.send(data);

Unless resorting to hacks like posting to a dummy target, AJAX is the way to go.

This works:

    const form =  document.querySelector("#message-form");
    form.addEventListener("submit", event => {
        event.preventDefault()

        let status = "";
        const data = new FormData(form);
        const req = new XMLHttpRequest();
        try{
            req.open("POST", '/send-message');
            req.send(data);
            status = "success";
        }
        catch{
            status = "failure";
        }
        notifyuser(status);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM