简体   繁体   中英

How to send an image file store in a variable to php using jQuery

I want to send an image file to PHP file using jQuery, by first storing the image in a variable and then send it for processing. The php code outputs an error like this:

Undefined index: img in C:\\xampp\\htdocs\\edash\\admin\\checks\\a_addQuest.php on line 2

This is the html code.

<input type="file" name="img" id="img">

This is my js code.

$("#submitQuest").click(function() {
    var  dataString;
    var img  = $("#img")[0].files[0];
    dataString   = "img="+img;

    $.ajax({
       type : "POST",
       url  : "../admin/checks/a_addQuest.php",
       data : dataString,
       success: function (result) {
            $("#output").html(result).fadeIn("slow", function () {
            $("#output").fadeOut(3000);
        });
     }
  });
  return false;
});

And This is the php file.

<?php
     $img = $_FILES['img']['name'];
     if($img){
           echo "working";
     }
?>
$("#submitQuest").click(function() {
    var data = new FormData();
    data.append('file', $('#img')[0].files[0]);

    $.ajax({
       type : "POST",
       url  : "../admin/checks/a_addQuest.php",
       data : data,
       cache: false,
       contentType: false,
       processData: false,
       success: function (result) {
          $("#output").html(result).fadeIn("slow", function () {
              $("#output").fadeOut(3000);
          });
       }
    });
    return false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM