简体   繁体   中英

Pure Javascript Ajax request after submitting a form

I'm not very good at programming, I'm trying to make a contact form and send the information with a response in the same page.

<form id="contact_form" method="post" action="send.php">

// fields

</form>

send.php contains a PHPMailer function to send the mail and other controls, so if js is disabled the user will be redirected to index.php with a success or error message.

But when js is active a validate function checks if all fields are filled and then start an ajax request, this is the code inside js.js file

function validate(e) {
    if (error_type === 1) {
            e.preventDefault();
            // display errors for every fields
        } else {

            var url = "send.php";
            var params = fileds_value;
            xhttp = new XMLHttpRequest();
            xhttp.open("POST", "url", true);
            xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhttp.onload = function() {
                if (xhttp.readyState == 4 && xhttp.status === 200 && xhttp.responseText) {
                    //display success message

                }
                else if (xhttp.status !== 200 || !xhttp.responseText) {
                    //display error message

                }
            };
            xhttp.send(JSON.stringify(params));
         }

    }}
window.onload = function() {
    document.getElementById("contact_form").addEventListener("submit", function(e){
        validate(e);
    });
};

I need to send the form data with the request to prevent the page to being refreshed, right?

and in send.php

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'XMLHttpRequest') {

  header('Content-Type: application/x-www-form-urlencoded');
  echo $ajax_message;
}
// else just display the message
else {

  redirect_to($message);
}

But after pressing the submit button the page is realoaded and I see the PHP success message, my goal is to make the page display the success message using ajax, without reloading the page.

EDIT: @IncredibleHat I edited the code to show how the event is handled, so I have to always prevent the default behavior and send the form data like that, then in php I can get the post variables like always?

use event.preventDefault(); , at the top of your event handler, instead of wrapping it within a condition.

if your form is inside other html elements, try also event.stopPropagation(); , as it stops the event from bubbling up and being handled by listeners from parent elements

in the end you would have something like:

form.addEventListener('submit',function(){
    event.preventDefault();
    event.stopPropagation();

    if (error_type === 1) 
         //doWhatever
    //..... perform ajax request
})

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