javascript - 如何在显示甜蜜警报后使用ajax在php中上传文件?

标签 javascript php jquery ajax

我目前在将文件输入(图像)插入数据库时​​遇到问题,但当我尝试将其插入数据库时​​,它返回空值。

这是我的脚本

<script>
        $("#insertform").on('submit',(function(e) {
/*          $('#submit').toggleClass('active');
            document.getElementById('submit').disabled = 'disabled'; */
            var data=$('#insertform').serialize();
            e.preventDefault();
            swal({   
                title: "Are you sure",   
                text: "Do you want to save hotel data",   
                type: "info",   
                showCancelButton: true,   
                closeOnConfirm: false,   
                showLoaderOnConfirm: true, }, 
                function(){   
                    setTimeout(function(){      
                    $.ajax({
                        url: "hotels/insert_Hotel.php",
                        type: "POST",
                        data: new FormData(this),
                        async: false,
                        success: function(data){
                            swal("Saved! your hotel data has been saved");
                            location.reload();
                        },
                        contentType: false,
                        cache: false,
                        processData:false, 
                        error: function(){
                            alert('error handing here');
                        }
                    });    
                    }, 2000); 
                }); 
        }));
    </script>

这是我的 php 文件

<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['logo']['tmp_name'])) {
$randomvalue=rand(1,999999999);
$date=date("Y-m-d H:i:s a");
$sourcePath = $_FILES['logo']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT']."/hotelLogos/".$randomvalue.$date.$_FILES['logo']['name'];
$dbpath="../../hotelLogos/".$randomvalue.$date.$_FILES['logo']['name'];
move_uploaded_file($sourcePath,$targetPath);
}
else{
    echo 'file not uploaded';
}
}
?>

它不会将文件上传到文件夹中,也不会将值插入到表中...

最佳答案

new FormData(this) 这里 this 不是表单,而是您需要在 new FormData(form) 中传递表单在 Ajax :

data: new FormData($('#insertform')[0]), // <---change to this.

关于javascript - 如何在显示甜蜜警报后使用ajax在php中上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33229945/

相关文章:

javascript - 使用 Javascript 访问 JSON 时使用 indexOf

javascript - 获取 Svg 中字符串的像素长度

javascript - RequireJS:多个 main.js?

PHP - 响应传入的 API 调用而不返回

jquery - 在 Magnificent Popup 中更改 ID 小对话框名称

Jquery $(this) 子选择器由于某种未知原因无法工作

javascript - 迭代映射键

php - 将 PHP 连接到 MySQL。我的电脑安装了2个MySQL。连接哪一个

php - 样式下拉中心选择标签在 chrome 和 firefox 中的选项

javascript - 创建包含 jquery 的 js 文件时出现错误