1

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>

6
  • where's your success/error function callback? Commented Jul 12, 2019 at 7:56
  • you should not use the submit button for the call of an ajax. change the button to a type="button", and put an eventobserver on that button. Commented Jul 12, 2019 at 8:00
  • Will do, thanks for the advice. Success/Error function is next on the list, but I was waiting until i'd figured out what was causing the crash before I implemented them. Commented Jul 12, 2019 at 8:10
  • @FatFreddy that's not fully true. You can just use e.preventDefault() - the type of button doesn't really matter. Commented Jul 12, 2019 at 8:11
  • @treyBake ofcourse you can use a preventDefault(), so its your turn to explain it to TatTheFlame :)) Commented Jul 12, 2019 at 8:17

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Of course - it's been bugging me for hours, I feel incredibly stupid now! Thanks for your help
1

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');
    });
});

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.