简体   繁体   中英

Using ajax/php to display message on form

I am trying to create ajax and php files so when a user enters data on the form it either displays an error message if its invalid or sends and email and displays a thank you message if it is valid. I am stuck and not sure why my code is not working, right now when I hit submit the page is just reloaded with no messages at all.

AJAX code:

$('document').ready(function () {

    var request;

    $('contact').submit(function(event) {

        event.preventDefault();

        if (request) {
            request.abort();
        }

        var $form = $(this);

        var $inputs = $form.find("inputs, select, buttons, textarea");

        var serializedData = $form.serialize();

        $inputs.prop("disabled", true);

        request = $.ajax({
            url: "../send_email.php",
            type: "post",
            data: serializedData
        });

        request.done(function (msg) {
            alert(msg);
        });

        request.fail(function (jqXHR, textStatus, errorThrown) {
            console.error(
            "The following error occurred: "+
            textStatus, errorThrown
            );
        });

        request.always(function () {
            $inputs.prop("disabled", false);
        });

    });//contact event

});//document ready

PHP code:

    <?php
    if(isset($_POST['email'])) {

        $email_to = "email@address.ca";
        $email_subject = "Personal Website Contact Form";

        $error_message = "";

        if(!isset($_POST['first_name']) ||
                !isset($_POST['last_name']) ||
                !isset($_POST['email']) ||
                !isset($_POST['comments'])) 
        {
            $error_message .= 'Please fill in all fields.\n'
        }
        else{
            $first_name = $_POST['first_name']; // required
            $last_name = $_POST['last_name']; // required
            $email_from = $_POST['email']; // required
            $comments = $_POST['comments']; // required

            $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

            if(!preg_match($email_exp,$email_from)) {
                $error_message .= 'The Email Address you entered does not appear to be valid.\n';
            }

            $string_exp = "/^[A-Za-z .'-]+$/";

            if(!preg_match($string_exp,$first_name)) {
                $error_message .= 'The First Name you entered does not appear to be valid.\n';
            }

            if(!preg_match($string_exp,$last_name)) {
                $error_message .= 'The Last Name you entered does not appear to be valid.\n';
            }

            if(strlen($comments) < 2) {
                $error_message .= 'The Comments you entered do not appear to be valid.\n';
            }

            if(strlen($error_message) == 0) {


            $email_message = "Form details below.\n\n";


            function clean_string($string) {
                $bad = array("content-type","bcc:","to:","cc:","href");
                return str_replace($bad,"",$string);
            }

            $email_message .= "First Name: ".clean_string($first_name)."\n";
            $email_message .= "Last Name: ".clean_string($last_name)."\n";
            $email_message .= "Email: ".clean_string($email_from)."\n";
            $email_message .= "Comments: ".clean_string($comments)."\n";


            // create email headers
            $headers = 'From: '.$email_from."\r\n".
            'Reply-To: '.$email_from."\r\n" .
            'X-Mailer: PHP/' . phpversion();
            @mail($email_to, $email_subject, $email_message, $headers); 

            echo "Email Sent. Thank you, I will get back to you asap";
            }
            else{
                echo $error_message;
            }
        }
    }
    ?>
$('document')

should be:

$(document)

And I suspect

$('contact')

should be:

$('#contact')

Though we'd have to see your HTML to know for certain. What you have is looking for <contact> elements, of which there are none. Instead, I imagine you want to look for something like <form id="contact"> .

These are also wrong:

$form.find("inputs, select, buttons, textarea")

HTML elements aren't pluralized:

$form.find("input, select, button, textarea")

You have to be specific about your selectors. jQuery isn't going to be able to guess what you mean if it's close enough. It has to be exact. There are many options to use in the selectors , it's good to familiarize yourself with the basics.

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