PHP form post data not being received due to jQuery

杀马特。学长 韩版系。学妹 提交于 2019-12-13 07:17:03

问题


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 = 'admin@example.com';

$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


回答1:


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


来源:https://stackoverflow.com/questions/33966502/php-form-post-data-not-being-received-due-to-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!