3

I have this contact form and I'm trying to use jQuery/AJAX and PHP to have the field input values sent to me via email. Well, the email sends to me just fine, but without any of the field input. The email is just the $to and the $subject of the PHP mail() function. Please see code below. Any ideas, critiques, or suggestions are welcome. Thanks for your help!

$(document).ready(function() {    

$(function() {

// Get the form.
var form = $('#ajax-contact');

// Get the messages div.
//var formMessages = $('#form-messages');

// Set up an event listener for the contact form.
$("button").click(function(e) {

    // Stop the browser from submitting the form.
    e.preventDefault(e);

    // Serialize the form data.
    var formData = $(form).serialize();

    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData,
        success: function(result){
            $('#contact-name').val('');
            $('#contact-email').val('');
            $('#contact-website').val('');
            $('#contact-message').val('');
        },
        error: function(xhr,status,error){

        }
    });


});

});

});

<?php
require_once 'swiftmailer/lib/swift_required.php';

//Swift Mailer script

$filter = FILTER_SANITIZE_STRING;

//Grab POST Data
$name = filter_var($_POST['contact-name'], $filter);
$email = filter_var($_POST['contact-email'], FILTER_SANITIZE_EMAIL);
$website = filter_var($_POST['contact-website'], FILTER_SANITIZE_URL);
$message = filter_var($_POST['contact-message'], $filter);


//Create email body
$body = "Name: " . $name . "<br />" . "Email: " . $email . "<br />" .   "Website: " . $website . "<br />" . "Message: " . $message;

//Create Transport
$transport = Swift_SmtpTransport::newInstance("host", "port", "security")
->setUsername("username")
->setPassword("password");

//Create Mailer
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('New Form')
->setFrom(array("email" => "Lead from Contact form"))
->setTo(array('email', 'email' => 'Recipients'))
->setSubject('You have a new message!')
->setBody($body, 'text/html');

//Send Message
$result = $mailer->send($message);

if ($result) {

// Set a 200 (okay) response code. //http_response_code(200); echo "Thank You! Your message has been sent."; } else { // Set a 500 (internal server error) response code. //http_response_code(500); echo "Oops! Something went wrong and we couldn't send your message."; }

?>

3 Answers 3

6

Use val() function to get data from inputs

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

$("button").click(function(e) {
e.preventDefault();
    var ajax = {
        isSubmitting: false,
        send: function() {
            if(ajax.isSubmitting == false) {

                ajax.isSubmitting = true;
                var userName = $('input[name="contact-name"]').val(); 
                var userEmail = $('input[name="contact-email"]').val(); 
                var userWebsite = $('input[name="contact-website"]').val(); 
                var userMessage = $('input[name="contact-message"]').val(); 

                if(userName === "" || userEmail === "" || userWebsite === "" || userMessage === "") {
                    alert("Please fill out all required fields.");
                } 
                else {
                    $.post("mailer3.php", {
                        name: userName,
                        email: userEmail,
                        website: userWebsite,
                        message: userMessage

                    }, function(data) {

                        ajax.isSubmitting = false;

                    });
                }
            }
            else alert("Send only 1 email at a time.");
        }
    }

});

Try this using $.ajax:

$("button").click(function(){
     isSubmitting: false;
     var userName = $('input[name="contact-name"]').val(); 
     var userEmail = $('input[name="contact-email"]').val(); 
     var userWebsite = $('input[name="contact-website"]').val(); 
     var userMessage = $('input[name="contact-message"]').val(); 

    if(isSubmitting == false) {

    $.ajax({url: "mailer3.php",
            type:'POST',
            data:{
            name: userName,
            email: userEmail,
            website: userWebsite,
            message: userMessage
             },
            success: function(result){
               isSubmitting == true;
            },error(xhr,status,error){
               isSubmitting == false;
            }
    });

    }
});
Sign up to request clarification or add additional context in comments.

11 Comments

Thank you for the suggestion. I tried it, but the field input values are still not coming in the e-mail. The from address is also showing as my hosting account username @ the host URL which seems weird to me or I just don't know enough about it. But any other suggestions? My "name" attr's in jQuery match my HTML file and those in turn match my PHP, I'm at a loss. Thanks!
var_dump the post values and see them in the response if they are correct, if they are you have a problem with your mail function and variables
madalin ivascu, that's a good idea. Does that just go at the end of the PHP file. Sorry, not too knowledgeable about PHP. But that brings up something else a little weird. Where one would normally see the POST/Response etc. in Firebug's console, i'm not seeing that at all. Thanks!
that means your ajax request isn't happening
the method you are calling the ajax is not familiar to me from what i can see you are creating a object with your ajax request, why aren't you doing a simple $.ajax and than on success you hide the ajax form and display a mesaje?
|
1

As you are not using the jQquery val(); method to retrieve your input feild value whioch is why you are unable to get value. Use the chain method val() with the elements calling as shown below

`$(document).ready(function(e) { //e.preventDefault(); $("button").click(function(e) {

var ajax = {
    isSubmitting: false,
    send: function() {
        if(ajax.isSubmitting == false) {

            ajax.isSubmitting = true;
            var userName = $("input[name=contact-name]").val(); 
            var userEmail = $("input[name=contact-email]").val(); 
            var userWebsite = $("input[name=contact-website]").val(); 
            var userMessage = $("input[name=contact-message]").val(); 

            if(userName === "" || userEmail === "" || userWebsite === "" || userMessage === "") {
                alert("Please fill out all required fields.");
            } 
            else {
                $.post("mailer3.php", {
                    name: userName,
                    email: userEmail,
                    website: userWebsite,
                    message: userMessage

                }, function(data) {

                    ajax.isSubmitting = false;

                });
            }
        }
        else alert("Send only 1 email at a time.");
    }
} `

1 Comment

Thanks, but I did end up trying this and it suprisingly to me, it didn't work. I figured this was the solution, but still no data coming through the e-mail, just the $to and $subject. Any other suggestions? Thanks in advance!
0

I did end up figuring this out. My revised code is at the top is what I used to get the email sending with the data. Used SwiftMailer. Just have to finish up a couple things. Thanks for everyone's input on this!

Andrew

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.