使用基于ajax的客户端上传PHP文件不起作用

时间:2013-09-26 02:42:26

标签: javascript php jquery ajax forms

我有一个将图片上传到特定路径的表单。我在提交表单时没有使用此<form action="file.php">,而是使用ajax提交表单。数据已成功保存在数据库中,包括文件名,但图像根本没有上传。这有什么问题?我怎么能修好这个呢?谢谢您的帮助。这是我的代码:

form.php的

 <form method="post" name="new_category" id="product_category" enctype="multipart/form-data"> 
 <ul class="add_prod">
 <li>Category Title:<input type="text" name="category[title]" id="cat_title" value="" placeholder="Title" /> </li>
 <li>Category Description:<textarea rows="4" cols="40" name="category[description]"></textarea></li>
 <li>Category Image:<input type="file" name="image_file" id="cat_image" /></li>
 </ul>  
 </form>

file.js

$("#product_category").submit( function(){

    event.preventDefault();

   var data_category = $(this).serialize();
   var image = $("#cat_image").val();
   $.ajax({
       type: "post",
       url: "../wp-content/plugins/product_form/category_save.php",
       dataType: "json",
       data:data_category + "&image_file=" +image,
       success: function(data){
           if(data.notify == "Success"){
               console.log(data.notify);
           }
           else{
               console.log(data.notify);
           }
       } 

    });
 });

Save.php

<?php 
//establish connection
$con = mysqli_connect("localhost","root","","database"); 
//on connection failure, throw an error
if(!$con) {  
die('Could not connect: '.mysql_error()); 
} 

$folder = "../Dropbox/estacio/wp-content/plugins/product_form/img/";

if (is_uploaded_file($_POST['image_file']['tmp_name']))  {   
if (move_uploaded_file($_POST['image_file']['tmp_name'], $folder.$_POST['image_file']['name'])) {
     echo "File uploaded";
  } else {
     echo "File not moved to destination folder. Check permissions";
   }
  } else {
  echo "File is not uploaded.";
 } 



   //get the form elements and store them in variables
   $category_values = $_POST["category"]; 
   $image_url = basename($_POST["image_file"]);
   $image_field = "image_url";
   $data = array();

   //unset($view_all_info['Password2']);
   foreach($category_values as $field => $val){
    $data[] = "`".$field."` = '".$val."'";
   }

   array_push($data,"`".$image_field."` = '".$image_url."'");

   $sql = "INSERT INTO wp_product_category SET ".implode(',', $data);
   $ret = mysqli_query($con,$sql); 

   if($ret){
    $notification="Success";
   }
else{
  $notification="Failed";
   }

  echo json_encode(array('notify'=>$notification));

  mysqli_close($con);
 ?>

1 个答案:

答案 0 :(得分:0)

尝试检查$ _FILES ['image_file'] ['tmp_name']或$ _FILES ['cat_file'] ['tmp_name']而不是$ _POST,post只提供参数传递的文件名,而不是实际上传的内容。

还尝试将action ='category_save.php'添加到您的表单并使用ajaxForm代替

$("#product_category").ajaxForm(
{
dataType:'json',
success:function(json){
   console.log('success');
}
}).submit();

为输入表单使用不同的id和name标签也不是很明智。