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

时间:2015-10-20 06:56:14

标签: 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';
}
}
?>

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

1 个答案:

答案 0 :(得分:0)

new FormData(this)此处this不是表单,而是您需要在ajax中的new FormData(form)中传递表单:

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