当尝试使用AJAX发送FormData时,表单数据不会通过? [英] Form data not going through when try to send FormData using AJAX?

查看:200
本文介绍了当尝试使用AJAX发送FormData时,表单数据不会通过?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新

由于 John Conde 建议,我会尝试更精确地描述我的问题。

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

  $(form [name ='add-event-form'])。 
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'])。
var end_date = $(this).find(input [name ='end_date'])。val();
var end_time = $(this).find(input [name =' 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 d ata = {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({$ b $ url:'ajax / addevent.php',
method :'POST',
processData:false,
contentType:false,
data:data,
dataType:'json',
error:function(error){
console.log(error);
},
成功:函数(json){
console.log(json);
},
完成:function(jqXHR,textStatus){
console.log(`AJAX认为登录请求是$ {textStatus}`);
}
});

$ / code>

然而,我知道没有任何事情要经过b / c我回来的对象从AJAX调用有以下错误:


我知道我的 data 对象我发送了 AJAX 调用被填写了b / c我打印出来了:



显然,我的数据对象没有被发送到我的 addevent.php 出于某种原因。我认为它是 processData:false,contentType:false 的b / c。我这样做的原因是B / C我试图上传一个文件在我的 addevent.php 这篇文章说在我的AJAX调用中要做 processData:false,contentType:false 如果你知道我在做什么错,请告诉我,谢谢!



代码



addevent.php

 <?php 
session_start();
require_once'../config-db.php';
$ b $ //设置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);

//设置返回
$ error ['error'] = array();
$ b $ // 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未成功移动;
}
$ _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'] [] =没有必填字段:$领域;



if($ field ==='title'){
$ value =(!empty($ _ POST [$ field])) $ _POST [$ field]:无标题;
} 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;
}
$执行= $ stmt->执行($ 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);
?>


解决方案使用 formData .submit()中使用这个来引用当前表单。


$ b $

  $(form [name ='event-form'])。submit(function(e){
e.preventDefault ();
var formData = new FormData(this);
$ .ajax({
url:'ajax / addevent.php',
type:'POST',
data:formData $ b $ dataType:'json',
error:function(error){
console.log(error);
},
contentType :false,//需要,不要忽略这个(需要jQuery 1.6+)
processData:false,//需要,不要忽略这个
成功:function(json){
console.log(json);
},
complete:function(jqXHR,textStatus){
console.log(`AJAX认为登录请求是$ {textStatus}`);
}
});
});


Update

Since John Conde has suggested it I will try to describe my problem more precisely.

In main.js I am trying to send my form object to addevent.php upon submission. How I do that is by selecting the form objects and creating a FormData object and sending that to addevent.php using AJAX:

$("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}`);
            }
          });
        }

However, I know nothing is going through b/c the object I get back from AJAX call has the following errors:

I know my data object I'm sending in the AJAX call is filled out b/c I have printed it out:

So clearly, my data object is not being sent to my addevent.php for some reason. And I think it's b/c of processData: false, contentType: false. The reason I did that was b/c I'm trying to upload a file in my addevent.php and this post said to do processData: false, contentType: false in my AJAX call.

Please let me know if you know what I am doing wrong, thanks!

Code

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);
?>

解决方案

Use formData, in your .submit() use this to refer to the current form.

$("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}`);
        }
    });
});

这篇关于当尝试使用AJAX发送FormData时,表单数据不会通过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆