Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST a form with Jquery AJAX When input is a File

Tags:

jquery

post

I have several areas where I use AJAX to submit text fields.

 var name = $("input#name").val(); 

   $.ajax({  
      type: "POST",  
      url: "bin/process.php",  
      data: "&name=" + name,  
      success: function() {  
       //handle response here
     }  
    }); 

However, I can't figure out how to do this if the input type is a file? Doing

var name = $("input#file").val(); doesn't seem to work..

like image 741
tpow Avatar asked Jan 04 '11 19:01

tpow


People also ask

How do I upload a file to FormData?

You can upload the selected file by creating a FormData class and passing it to Axios' post() function. const input = document. querySelector('#my-input'); const formData = new FormData(); formData. append('myFile', input.

How use Enctype multipart form data in AJAX?

2.1 Create a Javascript FormData object from a form. $. ajax({ type: "POST", enctype: 'multipart/form-data', processData: false, // Important!

Can we upload file using AJAX?

File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .


1 Answers

By default, jQuery cannot POST a form via AJAX if it contains a upload field.

You can try this plugin: http://jquery.malsup.com/form/

like image 115
Rocket Hazmat Avatar answered Oct 13 '22 01:10

Rocket Hazmat