dongyan1974 2010-10-20 09:13
浏览 44
已采纳

Ajax表单不起作用(jQuery - PHP)

jQuery:

$("#contact-us-form").submit(function () {
    var nameVal = $("input[name=name]").val();
    var companyVal = $("input[name=company]").val();
    var titleVal = $("input[name=title]").val();
    var emailVal = $("input[name=email]").val();
    var phoneVal = $("input[name=phone]").val();
    var messageVal = $("input[name=message]").val();
    $.post("mailer.php", {
        name: nameVal,
        company: companyVal,
        title: titleVal,
        email: emailVal,
        phone: phoneVal,
        message: messageVal
    }, function (data) {
        alert("Data Loaded: " + data);
        $('#thanks').show();
    });
    return false;
});

mailer.php:

<?php

if(isset($_POST['submit'])) {

    $to = "admin@domain.com";
    $subject = "Inquiry";
    $name = $_POST['name'];
    $company = $_POST['company'];
    $title = $_POST['title'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];

    $body = <<<HEREDOC
        From: $name
        Company: $company
        Title: $title 
        E-Mail: $email
        Phone: $phone 

        Message: $message 
HEREDOC;

    echo 'success';
    mail($to, $subject, $body);

} else {
    echo "failure";
}

?>

The data alert on the page returns failure, I don't understand why!

Thanks for your help!

  • 写回答

3条回答 默认 最新

  • drz73366 2010-10-20 09:32
    关注

    Two things, first the main issue is there is no submit variable you're passing (if there's a submit button it is not serialized like it would be in a normal post), so you have to add it. Also, you can really shorten you code by using .serialize() to serialize the <form> here, like this:

    $("#contact-us-form").submit(function () {
      $.post("mailer.php", $(this).serialize(), function (data) {
        alert("Data Loaded: " + data);
        $('#thanks').show();
      });
      return false;
    });
    

    To add your submit variable in there just use .serializeArray() and add it in, do this:

    $("#contact-us-form").submit(function () {
      var fdata = $(this).serializeArray();
      fdata.push({ name: 'submit', value: true });
      $.post("mailer.php", fdata, function (data) {
        alert("Data Loaded: " + data);
        $('#thanks').show();
      });
      return false;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度