0

Why isn't the form submitted the first time?
What have I done wrong?

If I click submit, the console will display the output (Event check # 0. Event check # 1.)
If I click on the submit button again, the console will display the output (Event check # 0. Event check # 1. Event check # 2.)
And after that the message will be sent to the mail.

enter image description here

".button-f" and "# send-btn-form" are the same button!

//#1grn --- Submitting the form without reloading the page
let sendBtn = document.querySelector(".button-f");
sendBtn.onclick = function(e) {
    e.preventDefault(); // Cancels the default browser action
    console.log("Event check №0.");

    let formName = document.querySelector('#main-form'); // Find our shape
    let formData = new FormData(formName); // Create a new FormData-object. We use all fields with the attribute name
    let request = new XMLHttpRequest(); // Create a new XMLHttpRequest-object.
    request.open('POST', "php/send.php"); // We configure it: POST-request for URL php/send.php

    //#1grn --- Filtering characters such as: &<>"'
    ['name', 'socialname', 'numberfo', 'email', 'text'].forEach(name => {
        let input = document.querySelector(`[name='${name}']`);
        input.value = escape(input.value);
        console.log("Event check №1.");
    });

    //#1grn --- Check ("real" event or generated by code)
    let sendBttn = document.querySelector("#send-btn-form");
    sendBttn.addEventListener('click', e => { // We accept the event object into our callback-function, call it "e".
        if (e.isTrusted) { // CHECKING, if a e.isTrusted === true - then this is not a machine click.
            request.send(formData); // We send HTTP request to the server and get a response.
            console.log("Event check №2.");
        } else {
            console.log('blocked!');
        }
    });

    // This code will work after we receive the server response
    request.onload = function() {
        if (request.status != 200) { // analyze HTTP-response status, if the status is not 200, then an error has occurred
        } else { // if everything went smoothly, clear the form and display the result
            formName.reset(formData); // Clearing the form
            let on = document.querySelector(".message-good");
            on.classList.add('ms-on');
        }
    };
};
Brendan8c
  • 369
  • 2
  • 11

1 Answers1

0

If ".button-f" and "#send-btn-form" are the same button, you are adding an event listener every time you click the button. In that case, you are not executing the code inside that listener, it will be executed the next time you click it. So you could replace this

let sendBttn = document.querySelector("#send-btn-form");
sendBttn.addEventListener('click', e => {
    if (e.isTrusted) {
        request.send(formData);
    } else {
        console.log('blocked!');
    }
});

with just this

if (e.isTrusted) {
    request.send(formData);
} else {
    console.log('blocked!');
}
Lucas Said
  • 801
  • 7
  • 5
  • Yes ".button-f" and "# send-btn-form" are the same button. If I remove this, then how will my verification take place? (Was it a real click or was it a bot) let sendBttn = document.querySelector ("# send-btn-form"); sendBttn.addEventListener ('click', e => { – Brendan8c Feb 19 '21 at 16:48
  • `sendBtn.onclick = function(e)` is the same as `sendBtn.addEventListener('click', e =>`, and I'm not sure about how any of those could check if it was a bot or a user who clicked... I think they both will fail at checking that – Lucas Said Feb 19 '21 at 16:53
  • The `isTrusted` read-only property of the `Event` interface is a `Boolean` that is `true` when the event was generated by a user action, and `false` when the event was created or modified by a script or dispatched via `EventTarget.dispatchEvent()` – Brendan8c Feb 19 '21 at 16:57
  • Oh alright, so look at my example, when it does `if (e.isTrusted)` that `e` is comming from the `onclick` event, so I think you'll be fine with it... In any case, always be careful about where an `addEventListener` is placed because it can harm the performance and it can also work wierd – Lucas Said Feb 19 '21 at 17:08
  • Yes thank you man! It worked! I checked all the functions and they work including the check from the bot. Yes i understood where had this problem. You rarely use `addEventListener`? – Brendan8c Feb 19 '21 at 17:24
  • Glad I could help! I use React so I rarely (actually never) use addEventListener... But it is ok to use it as long as you are careful about it... About difference between onclick and addEventListener('click'), I've found this [https://stackoverflow.com/a/6348597/6750370](https://stackoverflow.com/a/6348597/6750370) Hope it helps – Lucas Said Feb 19 '21 at 18:33