Uploading image via an AJAX function is easy and simple to implement in out page. In a previous tutorial, we have seen PHP image upload example without AJAX. In this example, I have added code for doing PHP image upload with AJAX without reloading the page.
I use jQuery AJAX to implement image upload. There is a form with file input field and a submit button. On submitting the form with the selected image file, the AJAX script will be executed. In this code, it sends the upload request to PHP with the uploaded image. PHP code moves the uploaded image to the target folder and returns the image HTML to show the preview as an AJAX response.
The following code shows the HTML for the image upload form. On submitting this form the AJAX function will be called to send the request to the PHP image upload code.
<form id="uploadForm" action="upload.php" method="post"> <label>Upload Image File:</label><br/> <input name="userImage" type="file" class="inputFile" /> <input type="submit" value="Submit" class="btnSubmit" /> </form>
This code shows the ajax() function used to send the file upload request by posting the FormData instance. In PHP, it uploads the file to the specified path. After successful image upload, it will print the uploaded image HTML as the AJAX in response. Then, this will be added to a target DIV to show the preview for the users.
After uploading an image via AJAX, we are showing preview for the uploaded image in the target div as shown below.