-2

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);
Colin
  • 4,025
  • 21
  • 40
  • If your javascript is just going to find the form and call submit, then there is no reason for this logic. Just make a submit button and let the form submit. – Taplar Nov 18 '20 at 22:18
  • If you do not want the page to perform a transfer for the form submit, then you either have to change it to do an ajax submit, or add a `target="..."` to the form so it will open the results in a new window or in a (hidden) iframe. – Taplar Nov 18 '20 at 22:19
  • @Taplar - There's more elaborate logic where the code is commented, but it's omitted because it's not relevant to the question. Can you elaborate on the hidden iframe approach? I'm not sure I'd favor it over AJAX, but it would be interesting to know the detail. – Colin Nov 18 '20 at 22:24
  • 1
    Essentially you make an ` – Taplar Nov 18 '20 at 22:26
  • @Taplar - I see. Thank you. That's interesting, but feels a bit inelegant. I may just relent and resort to AJAX. :-\ – Colin Nov 18 '20 at 22:30

1 Answers1

0

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);
    });
Colin
  • 4,025
  • 21
  • 40
hossein sedighian
  • 1,711
  • 1
  • 13
  • 16