使用formData使用ajax将图像插入数据库

insert image into database with ajax using formData

本文关键字:使用 插入 数据库 图像 formData ajax      更新时间:2023-09-26

我在从html表单上传图像时遇到了一些困难。表单应该能够将图像名称和其他数据一起发送到php页面。

我使用了formData而不是序列化函数,因为它不能处理文件数据。

$(document).on('click', '#btn_add', function(){
    var formData = new FormData($(this)[0]);
    $.ajax({
        url:"includes/widgets/insert.php",
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false
        success: function (data) {
            alert(data);
        },
    });
    return false;
});

html表单

 <form id="insert_post" action="includes/widgets/insert.php" method="post" enctype="multipart/form-data" >

         <div class="row">
             <div class="medium-6 columns">
                 <label>First name
                     <input type="text" name="first_name" id="first_name" contenteditable>
                 </label>
             </div>
             <div class="medium-6 columns">
                 <label>Last name
                     <input type="text" name="last_name" id="last_name" contenteditable>
                 </label>
             </div>
             <div class="medium-12 columns">
                 <label>Last name
                 <input  type="file" name="file" id="image" multiple contenteditable>
                 </label>
             </div>
             </div>
              <button type="button" name="btn_add" id="btn_add" class="button btn btn-xs btn-success" >Submit</button>

     </form>
php page
<?php
$connect = mysqli_connect("localhost", "root", "", "myaddboard");
echo $_POST['first_name'];
echo $_POST['last_name'];

echo $image = $_FILES['file']['name'];
echo $image_tmp = $_FILES['file']['tmp_name'];
/*
if(empty($image)){
    echo 'error';
}
move_uploaded_file($image_tmp,"img/$image");
  //$sql = "INSERT INTO posts(post_content, post_author) VALUES('".$_POST["first_name"]."', '".$_POST["last_name"]."')";
if(mysqli_query($connect, $sql))
{
    echo 'Data Inserted';
} else {
    echo 'error';
}
*/
?>  

php表单只是为了测试ajax是否正确发送数据。

当我点击按钮时,我总是会收到php变量没有定义的错误

我每次提交表格时都会出现错误

undefined index: frist_name in c:xampp'htdocs'unv'includes'widgets'insert.php on line 4
undefined index: last_name in c:xampp'htdocs'unv'includes'widgets'insert.php on line 5
undefined index: file in c:xampp'htdocs'unv'includes'widgets'insert.php on line 8
undefined index: file in c:xampp'htdocs'unv'includes'widgets'insert.php on line 9

我应该怎么做才能让ajax将数据发送到php页面?

由于选择器是如何创建的,所以这将不起作用。

$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);

在上面的场景中,$(this)[0]将为您提供button的原始HTML解释。

您实际想要的是将按钮更改为submit类型,捕获form submit event,然后处理您的请求。

button type="submit" <-- change
$(document).on('submit', '#insert_post', function(e){
    e.preventDefault(); //stop default form submission
    //do the rest of your stuff here
});

现在$(this)[0]实际上是form而不是button