doulaozhi6835 2017-11-16 12:42
浏览 38
已采纳

AJAX序列化数据为空

I'm trying to post form data via AJAX.

When I remove the AJAX function and do a standard form POST method the data is being inserted into DB fine. When I console.log the serialized data of the form on submit it shows fine.

It's when the AJAX function is fired that the data seemingly disappears. The function fires as a success but no data is inserted and the formdata variable is seemingly empty. Can anyone shine any light on this?

Here's the code so far -

jQuery/AJAX -

$('#calendar-form').submit(function() {
  var formdata = $(this).serialize();
  console.log(formdata);
  $.ajax({
    url: "insert.php",
    type: "POST",
    data: formdata,
    success: function() {
      alert('success')
    },
    error: function() {
      alert('ERROR');
    }
  });

  return false;
});

HTML

<form id="calendar-form" action="" method="" accept-charset="utf-8">
    <input type="text" name="name" id="name">
    <input type="text" name="email" id="email">
    <input type="hidden" name="site" id="site" value="<? echo $_SERVER['HTTP_HOST'] ?>">
    <input class="submit" type="submit" name="submit" value="Submit">
</form>

PHP

try {
    $bd = new PDO("mysql:host=localhost;dbname=;charset=utf8", "", "");
        //  $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo 'Theres been an error while attempting to connect to the database';
    }

    if(isset($_POST['submit'])){
        $name = $_POST['name'];
        $email = $_POST['email'];
        $site = $_POST['site'];

        $sql = "INSERT INTO `users`(`name`, `email`, `site`) VALUES ('$name', '$email', '$site')";

        try {
            $query = $bd->prepare($sql);
            $query->bindValue(':name', $name, PDO::PARAM_STR);
            $query->bindValue(':email', $email, PDO::PARAM_STR);
            $query->bindValue(':site', $site, PDO::PARAM_STR);

            if($query->execute()){
                echo "Success";
            }else{
                echo "Failure";
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

Note: I've removed DB details for this post but they're there in code.

Console

name=Benji&email=email%40email.com&site=localhost%3A8888 - scripts.min.js:9:117

Network

Console - Network

  • 写回答

1条回答 默认 最新

  • dqt20140129 2017-11-16 14:01
    关注

    This is because jQuery's .serialize() does not include the submit button:

    No submit button value is serialized since the form was not submitted using a button.

    Check the console for the output of your console.log(formdata) - you'll see submit is missing. And since it is missing, the test you do on that value on the back end will fail:

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

    Exactly how to do solve this depends on what you're trying to do. If you just want to make sure the request was a POST (not a GET) you could use:

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    

    If you want to do basic validation, you could explicitly check each of the expected values are present:

    if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['site'])) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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