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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同