Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload using ajax and JavaScript function [duplicate]

Need a big favor! I'm trying to send uploaded file using JavaScript & Ajax, however not getting any success.

I want that when I upload the file, it will call the function myFunction(), and send the file to the PHP path(ajax.php) I've set.

Below is the code I've so far.

<script>
   function myFunction() {
      var x = document.getElementById("up");
      $.ajax({
         type: 'GET',
         url: 'ajax.php',
         data: {},
         beforeSend: function() {},
         success: function(data) {
            alert(data);
         }
      });
   }
</script>
<input type="file" name="images" id="up" onchange="myFunction()" />
like image 366
shrddha patel Avatar asked Sep 17 '26 17:09

shrddha patel


1 Answers

If you only have one image and are using your input in a form, you can get the object by using FormData().And sending it when you click on a submit button. When passing it to AJAX use the variable (formdata) to tell AJAX what data to send. Hope this helps:

  function myFunction(event){
       event.preventDefault();
      var formdata = new FormData();
     formdata.append("images[]",images);
      $.ajax({
        type: 'GET',
        url: 'ajax.php',
        data: formdata,
        beforeSend: function() {},
        success: function(data) {
           alert(data);
       }
     });
   }

If you are uploading multiple images:

  <form id="yourform" method="POST" enctype="multipart/form-data">
      <input type="file" name="images[]" id="up" onchange="myFunction()" 
    multiple/>
   </form>
like image 188
ticktock Avatar answered Sep 19 '26 06:09

ticktock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!