weixin_33724570 2015-09-14 16:18 采纳率: 0%
浏览 9

表单提交PHP ajax

I am setting up a form submission and having some troubles getting the Ajax to connect to the PHP and send the form info to the desired email address. Not an expert at this whole thing as its the first time I attempt AJAX to submit a form information.

Any input on what is going wrong is appreciated.

Thanks in advance

THIS CODE IS NOW ALL WORKING I have updated the question with the new code.

FORM:

    <form name="contactform" id="contactsubmit" action="form_action.php">
        <h2>contact form</h2>
        <hr>
        <label class="Tgrey">name</label>
        <input type="text" name="name" id="name" required>
        <label class="Tgrey">email</label>
        <input type="email" name="email" id="email" required>
        <label class="Tgrey">Telephone</label>
        <input type="tel" name="telephone" id="telephone" required>
        <br>
        <br>
        <label class="Tgrey">Telephone</label>
        <br>
        <textarea name="message" rows="10" cols="50" id="message" required></textarea>
        <br>
        <input type="submit" value="send">
    </form>

JQUERY/AJAX

$("form").submit(function(e)
{
    event.preventDefault();
    $.ajax(
    {
        'url' : $(this).attr('action'),
        'type' : "POST",
        'data' : $(this).serialize(),
        success:function(success)
        {alert("HEY")},
    });
});

PHP

   if(isset($_POST['name'], $_POST['email'], $_POST['telephone'], $_POST['message'])){

    $name = $_POST['name'];
    $email = $_POST['email'];
    $telephone = $_POST['telephone'];
    $message = $_POST['message'];

    $to  = "name@email.com";
    $subject = "Message from $name via Web:";
    $txt = "This message has come website: 

    $message 

    Contact details:
 
    Name: $name, Email: $email, Telephone: $telephone";
    $header = "From Website";

    mail($to,$subject,$txt,$headers);
}
  • 写回答

1条回答 默认 最新

  • George_Fal 2015-09-14 16:24
    关注

    $_POST['submit'] is not sent in the serialized form data. What you should do is check to see if the POST array has got data in it:

    if(!empty($_POST)) {.. // if not empty, proceed
    

    If you didn't want to change your PHP you could append &submit=submit to your variable holding the serialized data in your AJAX function:

    'data' : $(this).serialize() + '&submit=submit',
    

    In addition, as @Fred -ii- pointed out, you have some variables which are not set($subject (this is also missing from your form unless you intend to set it in the code) and $headers). You need to add some basic error checking to your scripts which will indicate these problems. Add error reporting to the top of your file(s) right after your opening <?php tag

    error_reporting(E_ALL); 
    ini_set('display_errors', 1);
    
    评论

报告相同问题?