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 铜与钢双金属板叠加在一起每种材料300mm长,18mm宽,4mm厚一端固定并加热至80℃,当加热端温度保持不变时另一端的稳态温度。ansys
  • ¥15 django5安装失败
  • ¥15 Java与Hbase相关问题
  • ¥15 后缀 crn 游戏文件提取资源
  • ¥15 ANSYS分析简单钎焊问题
  • ¥20 bash代码推送不上去 git fetch origin master #失败了
  • ¥15 LOL外服加入了反作弊系统,现在游戏录像rofl文件离线都无法打开
  • ¥15 在centos7安装conda
  • ¥15 c#调用yolo3 dll文件获取的数据对不上
  • ¥20 WPF 如何实现多语言,label 和cs(live Charts)中是否都能翻译