2016-11-22 73 views
-1

我試圖將我的php代碼轉換爲使用php到javascript ajax。你能否請我糾正我應該出錯,因爲我的PHP代碼仍然激活。發佈圖像從PHP到javascript

的html代碼:

<form method="post" enctype="multipart/form-data" action="testadd.php"> 
<input type="file" name="image" id="image"> 
<br/> 
<input type="submit" name="submit" value="upload" id="submit"> 
</form> 

PHP:

<?php 

     if(isset($_POST['submit'])){ 

      if(getimagesize($_FILES['image']['tmp_name']) == false){ 
        echo "Please select an image"; 
        echo "<br/>"; 

      }else{ 
       $image = addslashes($_FILES['image']['tmp_name']); 
       $name = addslashes($_FILES['image']['name']); 
       $image = file_get_contents($image); 
       $image = base64_encode($image); 
       saveImage($name, $image); 
      } 

     } 

     displayImage(); 

     function saveImage($name, $image){ 
      $con = new PDO("mysql:host=localhost; dbname=testimages", "root", ""); 
      $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
      $stmt = $con->query("INSERT INTO images(id, name, image) VALUES(38836929, '$name', '$image') ON DUPLICATE KEY UPDATE image='$image', name='$name'"); 
      $stmt->execute(); 
     } 
     function displayImage(){ 
      $con = new PDO("mysql:host=localhost; dbname=testimages", "root", ""); 
      $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
      $stmt = $con->query("SELECT * FROM images"); 
      $stmt->execute(); 
      while($result = $stmt->fetch(PDO::FETCH_OBJ)){ 
       echo '<img height="24" width="24" src="data:image;base64,' . $result->image . '">'; 
       echo '<br/>'; 
       echo $result->name . ' '; 
      } 
     } 

?> 

的javascript:

$(document).ready(function(){ 
    $("#submit").click(function(){ 

     var image = document.getElementById("image").value; 

     alert(" " + image); 

     if(image == ""){ 
      alert("please select image"); 
     }else{ 
      $.ajax({ 
       type: "POST", 
       url: "testadd.php", 
       data: "image=" + image, 
       success: function(data){ 
        if(data == success){ 
         alert("test"); 
        }else{ 
         alert("fail"); 
        } 
       } 

      }); 
     } 
     return false; 
    }); 
}); 

可否請你檢查什麼應該是爲了使問題得到解決。

+0

搜索,B4 u向... –

+0

你以爲我沒有搜索谷歌?爲什麼我會在這裏問我是否沒有在谷歌搜索?我只是想維護我寫的代碼,因爲在谷歌有很多方法如何做到這一點。我只是想知道與我的代碼相同的代碼有什麼問題。 –

+0

幾個人已經問過與你的問題相同的問題,這就是爲什麼我告訴之前提問谷歌 –

回答

0

AJAX必須有內容類型,過程數據來上傳一次對谷歌的圖像文件

   $.ajax({ 
        url: 'Your url here', 
        data: formData, 
        type: 'POST', 
        // THIS MUST BE DONE FOR FILE UPLOADING 
        contentType: false, 
        processData: false, 
        // ... Other options like success and etc 
        success : function(data){ 
         //Do stuff for ahed process.... 
        } 
       });