2015-10-20 71 views
1

我现在有一个麻烦,插入一个文件输入(图像)到我的数据库,但它会返回我空值,当我试图将其插入数据库。如何在php中显示甜蜜警报后使用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'; 
} 
} 
?> 

它不上传文件到文件夹,并不会插入值表...

+0

'它返回我空值'你不会返回任何值,除非有错误..?我会建议你阅读这个问题:http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously –

+0

我看到很多错误和问题,同时保存图像与AJAX。我建议你使用fileupload.js(https://blueimp.github.io/jQuery-File-Upload/)通过js上传文件。最好的。 –

回答

0

new FormData(this)这里this不是形式,而是你需要传递的形式,您new FormData(form)在阿贾克斯:

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

这会导致一个错误,'FormData'采用HTMLElement的形式,而不是一个jQuery对象。 https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData。你的意思是'FormData($('#insertform')[0])'? –

+0

@RoryMcCrossan对第一个建议是正确的,但是'this'是指那里的表单? – Jai

+0

谢谢::::为什么我们把表单ID后的[0]? – lahiru

相关问题