Form data not going through when try to send FormD

2019-09-15 10:25发布

This question already has an answer here:

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: enter image description here

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

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

1条回答
走好不送
2楼-- · 2019-09-15 11:04

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}`);
        }
    });
});
查看更多
登录 后发表回答