Uploading image to jquery ajax php server. Dynamic file loading with jQuery

How to upload any files, such as pictures, to the server using AJAX and jQuery? It's quite easy to do! And below we will analyze everything in detail.

In those “ancient” times, when there was no jQuery yet, or maybe there was one, but the browsers were not so sophisticated, uploading a file to a site using AJAX was a tedious task: through all sorts of crutches like iframes. I didn’t catch that time, and who cares now? But now something else is interesting - that saving files to the site is very simple. Even a webmaster who does not have experience and understanding of how AJAX works will be able to quickly figure out what’s going on. And this article will help him. If you back up these capabilities with WordPress functions, then securely processing and uploading files to the server becomes a completely trivial and even interesting task (for an example with WordPress, see the end of the article).

However, no matter how simple everything is, it should be noted that minimal experience working with files and basic knowledge of Javascript, jQuery and PHP are still required! At a minimum, you need to imagine how files are uploaded to the server, as in general outline AJAX works and you need to be able to read and understand the code at least a little.

The method described below is quite stable, and essentially relies on Javascript object new FormData() , which has basic support in all browsers.

For a more understandable perception of the material, it is divided into steps. That's all, let's fly...

AJAX Loading files: general example

It all starts with the presence of an input field of type file on the site. There is no need for this field to be part of the form (tag).

Thus, we have HTML code with a file field and an “Upload Files” button.

download files

Step 1. Data from the file field

The first step is to get the data of the downloaded files.

When you click on the file field, a window for selecting files appears. After selection, data about them is saved in the input field, and we need to “pick it up” from there. To do this, we will attach a function to the change JS event that will save the existing file field data in the JS variable files:

Var files; // variable. will contain file data // fill the variable with data when the field value changes file $("input").on("change", function())( files = this.files; ));

Step 2. Create an AJAX request (by click)

We have the file data, now we need to send it via AJAX. We assign this event to a click on the “Upload files” button.

At the moment of clicking, we create a new object new formData() and add data from the files variable to it. Using formData() we will ensure that the submitted data looks as if we had simply submitted the form in the browser.

For such a request to take place, you need to specify additional parameters in jQuery AJAX parameters, so the usual $.post() function is not suitable and we use a more flexible analogue: $.ajax() .

Two important additional parameters needs to be set to false:

ProcessData Disables processing of transmitted data. By default, for example, for GET requests jQuery collects the data into a query string and appends that string to the end of the URL. For POST data does other transformations. Any changes to the source data will interfere with us, so we disable this option... contentType Disables setting the request type header. Default jQuery installation is equal to "application/x-www-form-urlencoded". This header does not support sending files. If you set this parameter to "multipart/form-data", PHP will still not be able to recognize the data being transferred and will display a warning "Missing boundary in multipart/form -data"... In general, the easiest way is to disable this option, then everything works // processing and! AJAX sending request when you click on the upload_files button $(".upload_files").on("click", function(event)( event.stopPropagation(); // stopping all current JS events event.preventDefault(); // stopping the default event for current element - click for tag // do nothing if files is empty if(typeof files == "undefined") return;
"; )) $(".ajax-reply").html(html); ) // error else ( console.log("ERROR: " + respond.error); ) ), // server response error function error: function(jqXHR, status, errorThrown)( console.log("AJAX request ERROR: " + status, jqXHR); ) ));

Step 3. Process the request: upload files to the server

Now last step: the sent request needs to be processed.

To make it clearer, we will process the request without additional checks for files, i.e. just save the received files in the desired folder. Although, for security, sent files must be checked, at least the extension (type) of the file...

Let's create a submit.php file with the following code (it is assumed that submit.php is in the same folder as the file from which the AJAX request is sent):

jQuery(document).ready(function($)( // link to file AJAX handler var ajaxurl = ""; var nonce = ""; var files; // variable. will contain file data // fill the variable with data when changed field values ​​file $("input").on("change", function())( files = this.files; )); // processing and sending an AJAX request when clicking the upload_files button $(".upload_files").on ("click", function(event)( event.stopPropagation(); // stopping all current JS events event.preventDefault(); // stopping the default event for the current element - click for tag // do nothing if files is empty if(typeof files == "undefined") return;