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条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 结构体数组文件读取问题
      • ¥15 写c++代码,第7题说一下使用的计算方法
      • ¥15 postman接口自动化测试报告实践总结
      • ¥15 有关c++的问题,利用相关知识
      • ¥15 求香农编码和解码的matlab代码
      • ¥20 ROS中的TEB局部规划问题
      • ¥20 关于#matlab#的问题:要求测出上面图片中所有同心圆的半径
      • ¥20 epanet软件运行问题
      • ¥15 Python 文件读取
      • ¥60 dpabi进行Alff计算时脑池有干扰信号