heyitsmyusername
heyitsmyusername

Reputation: 651

PHP form post data not being received due to jQuery

I have a basic form to send an email. It is sending the email, but not passing the data from the form. Is there something I am missing to allow the data to POST?

HTML form to send email:

<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
    <div class="row">
        <div class="col-sm-5">
            <div class="form-group">
                <input name="name" type="text" class="form-control" required="required" placeholder="Name">
            </div>
            <div class="form-group">
                 <input name="email" type="text" class="form-control" required="required" placeholder="Email address">
            </div>
            <div class="form-group">
                 <button type="submit" class="btn btn-primary btn-lg">Send Message</button>
            </div>
        </div>
        <div class="col-sm-7">
            <textarea name="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>
        </div>
    </div>
</form>

PHP code in sendemail.php

<?php
header('Content-type: application/json');
$status = array(
    'type'=>'success',
    'message'=>'Email sent!'
);

$name = @trim(stripslashes($_POST['name'])); 
$email = @trim(stripslashes($_POST['email'])); 
$subject = "Example Contact";
$message = @trim(stripslashes($_POST['message'])); 

$email_from = $email;
$email_to = '[email protected]';

$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;

$success = @mail($email_to, $subject, $body, 'From: ' . $email_from);

echo json_encode($status);
die;

UPDATE: It looks like there is a problem in js/jquery when the class="contact-form" is included. If I leave it out, the variables are sent.

Here is the jquery code for the form:

//contact form
var form = $('.contact-form');
form.submit(function () {
    $this = $(this);
    $.post($(this).attr('action'), function(data) {
        $this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
    },'json');
    return false;
});

Here are some related posts:
PHP Blank Email
Contact form won't submit data
js deleting submitted form data
PHP script sending mails but not showing form data
Post Data is not coming

Upvotes: 0

Views: 183

Answers (1)

miken32
miken32

Reputation: 42744

You're calling jquery.post() but you only say where to post to, and what to do when it succeeds. What are you posting? The second parameter needs to be the data you're posting:

$.post($(this).attr('action'), $(this).serialize(), function(data) {
    $this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');

Upvotes: 1

Related Questions