2016-05-13 56 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

毫米它像一个魅力工作非常感谢你。上次我尝试提交类型时,它总是将我指向操作页面,所以我使用了按钮。但它现在正在工作,因为它应该。再次感谢 。 –