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,471
  • 17
  • 87
  • 173
Sugumar Venkatesan
  • 3,782
  • 7
  • 39
  • 71

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
  • 72,925
  • 12
  • 73
  • 99
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
  • 398
  • 3
  • 16