douchao1957
douchao1957
2016-06-07 08:24

使用PHP和AJAX在数据库中上传图像

Hiii Everyone,

I tried to upload image and i want to store image path in database using php and ajax.Here is my code.I tried with this but im getting error. i searched everywhere but i can't find the solution.

HTML page:

<form id="reg-form">
  <input name="image" type='file' class="inputFile" id="photo" ACCEPT="image/*"/>
 <a href='#' class='ph-button ph-btn-blue' id="register_translator">Register</a>
</form>

And my Javascript code

$('#register_translator').click(function (event)
         {
         event.preventDefault();
       $.ajax({
      url: "add_translator_image.php",
      type: "POST",
      data: new FormData(this),
      contentType: false,
      cache: false,
      processData:false,
      success: function(data){
      alert(data);
        },
        error: function(){}           
     });

    });

PHP code

<?php
date_default_timezone_set('Asia/Kolkata');
$date = date("Y-m-d");
$time = date("Y-m-d H:i:s");
require "translator.php";
if(is_array($_FILES)) 
{

foreach ($_FILES['image']['name'] as $name => $value)
{
if(is_uploaded_file($_FILES['image']['tmp_name'][$name])) 
{
$sourcePath = $_FILES['image']['tmp_name'][$name];
$targetPath = "uploads/".$_FILES['image']['name'][$name];
$reg = new translator();


    $add = $reg->add_translator_image($targetPath);

  echo $add;

}
}
}
?>

And in add_translator_image i just wrote insert query in database.Error is Undefined index: image.. Image is name given for input type file it is not taking value so simply wherever im using image it is showin undefined error.What is the mistake.I tried many times but i cant find the solution.If anybody know the solution please let me know as soon as possible.If you help me with this part i ll be grateful.Thanks in advance.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doqrjrc95405 doqrjrc95405 5年前

    new FormData must be call existed form id with index 0 [javascript standard object]..

    data: new FormData($('#reg-form')[0]),
    
    点赞 评论 复制链接分享