1

After submitting the form, I want to display success or error message by removing element id (id value display:none). Element contains the message text.

I can submit the form with this script, but instead showing me the element, new page is opened with JSON string.

What should be corrected in the script? vanilla Javascript

<script type="text/javascript">
        var form = document.getElementById("leadcontact");
        var sent = document.getElementById('sent');
        var notsent = document.getElementById('notsent');
        form.onsubmit = function(event) {
        event.preventDefault();
        var formData = new FormData(form);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", form.action, true);
        xhr.send(formData);
        xhr.onload = function(e) {
        if (xhr.status === 200) {
        sent.removeAttribute('id');
        form.reset();
        } else {
        notsent.removeAttribute('id');
        }
        };
        };
    </script>

the Form

<form id="leadcontact" action="xxxxxxxxxxx" method="POST" enctype="multipart/form-data">
                                <div class="form-field-container">
                                    <label for="name">name</label>
                                    <input type="text" name="name">
                                </div>
                                <div class="form-field-container">
                                    <label for="tel">phone</label>
                                    <input type="text" name="phone">
                                </div>
                                <div class="form-field-container">
                                    <label for="email">email</label>
                                    <input type="email" name="email">
                                </div>
                                <div class="form-field-container">
                                    <label for="message">message</label>
                                    <textarea name="message"></textarea>
                                </div>
                                <p id="notsent" class="message-status error">Error! Not sent</p>
                                <p id="sent" class="message-status success">Message sent</p>
                                <button type="submit">Send</button>                
                            </form>

JSON output page - the page shows after submission

{"success":true,"given_params":{"name":"","phone":"","email":"","message":""}}
  • It sounds like the submit event handler is never executed, and the form is submitted instead. Make sure the form exists at the time you're running the code in the example. – Teemu Sep 26 '22 at 09:54
  • it's unclear why, as you described, after submitting the form you get the json response in return. Considering your onsubmit handler, since you call preventDefault, it shouldn't behave like that. Please include also the html of your form (even just using bogus fields) and try to make the snippet consistent so the big picture gets more clear. Probably as @Teemu suggested, your form id `leadcontact` doesn't get selected at all and the handler doesn't get bound. – Diego D Sep 26 '22 at 10:00
  • I added the form –  Sep 26 '22 at 10:31
  • Notice, that your code doesn't submit a form, it specifically prevents form submission, and sends an XHR request instead. The code itself looks fine, I guess this question falls back to [this question](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). – Teemu Sep 26 '22 at 10:48
  • @Teemu Form submission is correct, I can receive senders form data. Problem is about showing page with JSON after submission instead element success message. –  Sep 26 '22 at 11:02
  • added the json output –  Sep 26 '22 at 11:08
  • It's not. You've now been adviced in multiple comments to check whether your code is run at all, why don't you just do that and stop arguing ..? Hit F12, and you'll see an error message: "Cannot set property of null.", targetting the line `form.onsubmit = ...`. – Teemu Sep 26 '22 at 11:10
  • Form represents a hyperlink, clicking on a submit button on a form behaves in the same way as you would click on `a` element (with `href` attribute). Even before a submit handler is executed, the browser prepares for the page navigation. That navigation will take place after the submit event has been executed, if it's not specifically not prevented (by calling `event.preventDefault` in the handler). Your code prevents the form submission, but the browser doesn't, and it navigates to a new page, which shows what ever your server has responded with. That means that your code is never executed. – Teemu Sep 26 '22 at 11:29
  • @Teemu Can you modify and show the correct code, please? –  Sep 26 '22 at 12:12
  • The script is fine, just place it at the end of body element. – Teemu Sep 26 '22 at 12:48
  • The solutions above not working. I need to find something else. –  Sep 26 '22 at 15:57

1 Answers1

0

You need to place the onload event handler before you send the request.

This is because the event handler is then attached to the request bwdire it is sent.

See Item 5

https://xhr.spec.whatwg.org/#the-send()-method

for more information on how send() works.

JMP
  • 4,417
  • 17
  • 30
  • 41
  • It's highly unlikely, that a request is responded before browser attaches the load listener. Anyway, when that's the case, the result would be "nothing happens", the location wouldn't be re-directed. – Teemu Sep 26 '22 at 10:52
  • @Teemu; The listener is attached when the request is **sent**. – JMP Sep 26 '22 at 10:57
  • Nope, it's attached when the line of JS code attaches a listener to the XHR object, only internal _upload listener_ flag is set on send (with that flag XHR handles `readyStateChange` events correctly, as that event fires also before the actual response). – Teemu Sep 26 '22 at 11:06