In this tutorial let us learn about how to upload an image file using PHP and AJAX. In the previous tutorial, we have seen PHP image upload via AJAX.
In this example, we are sending form data to the PHP script via jQuery ajax(). In PHP script it moves uploaded an image to the target folder and returns success message as AJAX response.
HTML code for the form containing file input is,
<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>
On submit, the AJAX call will be triggered to send form’s file input to the PHP page upload.php. The script is,
This AJAX call includes several options URL, Type, data and more. we are sending image file data by instantiating FormData. The success/failure handlers are triggered based on the result of the upload request.
Initially, the form will be,
After uploading an image via AJAX, we are loading the image to the target layer on the left side of the above form. So the output will be,
This PHP code tutorial was published on January 3, 2014.