0

I want to upload image using ajax I got the following code from the internet: How can I upload files asynchronously?

<script>
$(function(){
      $("#imgfile").on("click", function(){
      alert("hello");
        var formData = new FormData($('form')[0]);
        $.ajax({
            url: 'imageupload.php',  
            type: 'POST',
            xhr: function() {  
                var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){ 
                    myXhr.upload.addEventListener('progress',progressHandlingFunction, false); 
                }
                return myXhr;
            },
            success: function(data){
               alert(data);

            },
            error: function(){
              alert("error check it");
            },
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
      });
   </script>

and the html

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

I want the script to be executed when the user selects the image and ready to be processed. I don't want separate upload button. I tried and failed.

halfer
  • 19,824
  • 17
  • 99
  • 186
Sugumar Venkatesan
  • 4,019
  • 8
  • 46
  • 77

2 Answers2

1

I want the script to be executed when the user selects the image and ready to be processed. and I dont want separate upload button I tried and failed.

For this you have use change event instead:

$("#imgfile").on("change", function(){
     // all code
});

change event gets fired when you select a file in the input file element.

Jai
  • 74,255
  • 12
  • 74
  • 103
1

Alternate solution using jQuery and the AJAX Upload plugin seem to work for me. Try this http://zurb.com/playground/ajax-upload

Ananthu R V
  • 428
  • 4
  • 17