使用AJAX返回PHP数据

时间:2016-09-08 11:40:01

标签: php ajax

我正在慢慢学习如何构建完全自定义的CMS系统,并且目前正在构建一个Image Uploader。我得到了我的PHP表单,但我想要的是使用AJAX发送数据并将数据返回到upload.php文件。到目前为止,我已成功将表单数据发送到PHP,并将图像上传到我的uploads文件夹。我遇到的麻烦是,没有任何东西可以告诉我是否成功。我希望图像显示成功和错误消息,如果不成功。我没有使用Javascript或AJAX的经验,所以有人可以看看我的代码并告诉我哪里出错了?

HTML上传表格

<div class="container-main">
  <form action="" method="post" id="myForm" enctype="multipart/form-data">
    <input type="file" name="file" id="file"><br>
    <input type="submit" id="upload-img" name="submit" class="btn btn-success" value="Upload Image">
  </form>

  <div class="progress progress-striped active">
    <div class="progress-bar"  role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
      <span class="sr-only">0% Complete</span> 
    </div>
  </div>
  <div class="image">
  <!-- uploaded image goes here -->   
  </div>
</div>

<script type="text/javascript" src="js/custom.js"></script>

JS

$('#upload-img').on('click', function() {
    var file_data = $('#file').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
    alert(form_data);                             
    $.ajax({
                url: 'upload.php', // point to server-side PHP script 
                dataType: 'text',  // what to expect back from the PHP script, if anything
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,                         
                type: 'post',
                success: function(){
                    $(".image").html("<img src='"+response.responseText+"' width='100%'/>");

                }
     });
});

upload.php的

$allowedExts = array("gif", "jpeg", "jpg", "png","GIF","JPEG","JPG","PNG");

$temp = explode(".", $_FILES["file"]["name"]);

$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& in_array($extension, $allowedExts)) {

  if ($_FILES["file"]["error"] > 0) {
    echo "Invalid File Type";
  } else {
    $target = "../upload/";
    move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"]);
    echo  "../upload/" . $_FILES["file"]["name"];

  }
} else {
  echo "Error uploading image";
  die();
}

非常感谢!

1 个答案:

答案 0 :(得分:2)

您不需要使用.responseText属性(它不存在)

你的功能应该是这样的:

success: function(response){
                    $(".image").html('<img src="'+response+'" width="100%"/>');

                }

注意我改变了你的单引号/双引号。