2016-05-13 44 views
0

我有一些困難,從HTML表單上傳圖像。表單應該能夠將圖像名稱與其他數據一起發送到php頁面。使用formData插入圖像到數據庫與ajax

我使用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 

我應該怎麼做才能讓阿賈克斯發送數據到php頁面?

+0

什麼是錯誤..請發帖 – Poria

+0

我更新了問題。謝謝 –

回答

2

由於選擇器的創建方式,這不起作用。

$(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

+0

毫米它像一個魅力工作非常感謝你。上次我嘗試提交類型時,它總是將我指向操作頁面,所以我使用了按鈕。但它現在正在工作,因爲它應該。再次感謝 。 –