【问题标题】:Form data not going through when try to send FormData using AJAX? [duplicate]尝试使用 AJAX 发送 FormData 时表单数据不通过? [复制]
【发布时间】:2017-05-06 17:46:11
【问题描述】:

更新

既然 John Conde 提出了建议,我将尝试更准确地描述我的问题。

ma​​in.js 中,我试图在提交时将我的表单对象发送到addevent.php。我如何做到这一点是通过选择表单对象并创建一个FormData 对象并使用 AJAX 将其发送到addevent.php

$("form[name='add-event-form']").submit(function(e){
        e.preventDefault();
        var title = $(this).find("input[name='title']").val();
        var start_date = $(this).find("input[name='start_date']").val();
        var start_time = $(this).find("input[name='start_time']").val();
        var end_date = $(this).find("input[name='end_date']").val();
        var end_time = $(this).find("input[name='end_time']").val();
        var place = $(this).find("input[name='place']").val();
        var description = $(this).find("input[name='description']").val();
        var file = $(this).find("input[name='file']")[0].files[0];
        var fileData = new FormData();
        fileData.append('file', file);
        var data = {title: title, start_date: start_date, start_time: start_time,
                    end_date: end_date, end_time: end_time, place: place,
                    description: description, file: fileData};
        console.log(data);
        if(title && start_date && start_time){
          var event_form = $.ajax({
            url: 'ajax/addevent.php',
            method: 'POST',
            processData: false,
            contentType: false,
            data: data,
            dataType: 'json',
            error: function (error){
              console.log(error);
            },
            success: function (json){
              console.log(json);
            },
            complete: function (jqXHR, textStatus) {
              console.log(`AJAX thinks login request was a ${textStatus}`);
            }
          });
        }

但是,我知道什么都没有通过 b/c 我从 AJAX 调用返回的对象有以下错误:

我知道我在 AJAX 调用中发送的 data 对象已填写 b/c 我已将其打印出来:

很明显,我的data 对象由于某种原因没有发送到我的addevent.php。我认为这是processData: false, contentType: false 的b/c。我这样做的原因是 b/c 我试图在我的 addevent.phpthis post 中上传一个文件,据说在我的 AJAX 调用中执行 processData: false, contentType: false

如果您知道我做错了什么,请告诉我,谢谢!

代码

addevent.php

<?php
session_start();
require_once '../config-db.php';

//Set up SQL
$query = "INSERT INTO events (title, start_date, start_time, end_date, end_time, place, description)
          VALUES (:title, :start_date, :start_time, :end_date, :end_time, :place, :description)";
$fields = array('title', 'start_date', 'start_time', 'end_date', 'end_time', 'place', 'description');
$stmt = $db->prepare($query);

//Set up return
$error['error'] = array();

//N2SELF: N2Do DATA VALIDATION
if(!empty($_FILES['file'])){
  $image=$_FILES['file'];
  $file_name=$_FILES['file']['name'];
  $image_tmp =$_FILES['file']['tmp_name'];
  if($_FILES['file']['error'] === 0){
    $file_path = "images/";
    $move_successfully = move_uploaded_file( $image_tmp, $file_path.$file_name);
    if(!$move_successfully){
      $error['error'][] = "$image_tmp was not moved successfully";
    }
    $_SESSION['photos'][] = $file_name;
    $error['error'][] = "$image_tmp was moved successfully";
  }
}

foreach($fields as $field){
  if($field === 'title' || $field === 'start_date' || $field === 'start_time'){
    if(empty($_POST[$field])){
      $error['error'][] = "No required field: $field";
    }
  }

  if($field === 'title'){
    $value = (!empty($_POST[$field])) ? $_POST[$field] : "Untitled";
  }elseif($field === 'start_date'){
    $value = (!empty($_POST[$field])) ? $_POST[$field] : "NO DATE";
  }
  elseif($field === 'start_time'){
    $value = (!empty($_POST[$field])) ? $_POST[$field] : "NO TIME";
  }else{
    $value = (!empty($_POST[$field])) ? $_POST[$field] : NULL;
  }

  $parameter = ":$field";
  $paramToValues[$parameter] = $value;
}
$executed = $stmt->execute($paramToValues);
if(!$executed){
  $error['error'][] = "SQL query $query not executed";
  echo json_encode($error);
  exit();
}

foreach($fields as $field){
  $error['fields'][] = $_POST[$field];
}
echo json_encode($error);
?>

【问题讨论】:

  • 代码太多。您需要自己更好地解决此问题。我们不是调试器。您需要隔离问题并从那里进行调试。如果您遇到困难,请通过Minimal, Complete, and Verifiable example 提供关于什么不工作的明确解释。我建议阅读 How to Ask 一个好问题和 the perfect question。另外,请务必使用 tour 并阅读 this
  • @JohnConde 我知道问题所在:这是我的main.js,特别是data 对象的创建。我只是想包括其他文件,这样其他人就不会质疑我是否做错了与这个问题无关的其他事情(例如正确选择表单数据元素)。但是既然你建议我会删除我的html代码
  • 检查开发者工具网络标签以查看请求的内容。
  • @siddhesh 我在network 标签上。我不确定要点击什么来查看请求的内容?
  • 使用您的浏览器文档了解更多关于检查请求的信息

标签: javascript php jquery ajax file-upload


【解决方案1】:

使用formData,在您的.submit() 中使用this 引用当前表单。

$("form[name='event-form']").submit(function(e){
    e.preventDefault();
    var formData = new FormData(this);
    $.ajax({
        url: 'ajax/addevent.php',
        type: 'POST',
        data: formData,
        dataType: 'json',
        error: function (error) {
            console.log(error);
        },
        contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
        processData: false, // NEEDED, DON'T OMIT THIS
        success: function (json) {
            console.log(json);
        },
        complete: function (jqXHR, textStatus) {
            console.log(`AJAX thinks login request was a ${textStatus}`);
        }
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2022-11-26
    相关资源
    最近更新 更多