简体   繁体   中英

Running a PHP Script without changing page

I've set up a PHP script to collect "POST" data from a HTML form and send an email to a specific account with the data collected (a simple contact form).

I've created the PHP script which works correctly when the data is submitted using the submit button in the form, but want this takes me to a new page (the output of the PHP script).

I'd like to be able to keep this on one page, potentially displaying a message once the data has been sent correctly. I know I will need to use AJAX for this, so I've attempted to implement the jQuery AJAX method with little success.

When submitting the form, the page loads for a long time then quickly flashes an error message in the console before refreshing (I can't catch this error message to debug). Have I missed something in the JavaScript? Any assistance would be greatly appreciated.

My JS Code is as follows:


var submitBtn = $('#submit-form');

submitBtn.click(function(){
    let email = $('#email'), 
    forename = $('#forename'), 
    surname = $('#surname'), 
    subject = $('#subject'), 
    message = $('#message');
    // Send data to PHP script
    $.ajax({
        url: "submit_form.php",
        method: 'POST',
        data: {email: email, forename: forename, surname: surname, subject: subject, message: message}
    });
});

My PHP Script:


    $from_add = ; // Removed for security
    $to_add = ; // Removed for security
    $user_email = $_POST['email'];

    $subject = $_POST['subject'];
    $message = "You have received a message from {$_POST['forename']} {$_POST['surname']}:\n{$_POST['message']}";

    $headers = "From: $from_add \r\n";
    $headers .= "Reply-To: $user_email \r\n";
    $headers .= "Return-Path: $from_add\r\n";
    $headers .= "X-Mailer: PHP \r\n";


    if(mail($to_add,$subject,$message,$headers)) 
    {
        echo "Email Sent";
    } 
    else 
    {
       echo "Error sending email!";
    }

My HTML Form:


<form id="contact-form" class="contact-form">
            <p class="field-label">First Name:</p>
            <input class="input-field" type="text" id="forename" name="forename" placeholder="Please Enter Your First Name..." required>
            <p class="field-label">Last Name:</p>
            <input class="input-field" type="text" id="surname" name="surname" placeholder="Please Enter Your Last Name..." required>
            <p class="field-label">Phone Number (Optional):</p>
            <input class="input-field" type="text" id="phone" name="phone" placeholder="Please Enter Your Phone Number...">
            <p class="field-label">Email Address:</p>
            <input class="input-field" type="text" id="email" name="email" placeholder="Please Enter Your Email Address..." required>
            <p class="field-label">Message Subject:</p>
            <input class="input-field" type="text" id="subject" name="subject" placeholder="Message Subject" required>
            <p class="field-label">Your Message:</p>
            <textarea class="input-field" id="text-area" id="message" name="message" placeholder="Start typing your message here..." required></textarea>
            <button id="submit-form" type="submit">Send Message</button>
        </form>

You taking value incorrectly:

let email = $('#email');
// email will be jQuery instance of DOM element #email

Will return value:

// Get the value from an element directly
$( "select#foo" ).val();

Also replace button type to "button" to prevent from submission:

<button id="submit-form" type="button">Send Message</button>

You are passing input elements themselves instead of their value! to get their value you need to call .val() . More over you need to provide a callback function to handle response. Please take a look at this code:

$('#submit-form').on("click", function(e){
    e.preventDefault();
    var data = {
        email: $('#email').val(),
        forename: $('#forename').val(),
        surname: $('#surname').val(),
        subject: $('#subject').val(),
        message: $('#message').val()
    }

    // Send data to PHP script
    $.post("submit_form.php", data, function(res) {
        // $("#status").html(res);
        console.log(res);
        alert('Done');
    });
});

First of all, elements can't have 2 id attributes set, but your textarea does.

To correctly get the value of an input element, you'll need to select the element with $('#elementid') and then chain the val() function like so: $('#elementid').val().

The form will be triggered by pressing the submit button, so you'll need a listener on the forms 'submit' event, in the callback function you'll put your 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