Uploading An Image Using AJAX In jQuery With PHP

Read {count} times since 2020

As you know AJAX is the method of sending data without refreshing the page. Now I’m going to tell you how to upload images using AJAX in jQuery. For This You need to Download the jquery.form plugin from here. The Minimum requirement for this plugin is jQuery version 1.5 or later.

A Sample of uploading image using AJAX in jQuery is shown below :

  Now Let&#8217;s start on the code. Here is the <b>HTML</b> page :

  <pre class="prettyprint"><code>&lt;!DOCTYPE html&gt;

<html> <head> <script src="//code.jquery.com/jquery-latest.min.js"></script> <script src=“http://malsup.github.io/jquery.form.js"&gt;&lt;/script> </head> <body> <form action=“upload.php” method=“POST” id=“uploadform”>   <input type=“file” name=“file”/>   <input type=“submit” value=“Upload”/><br/><br/>   Message :   <div id=“onsuccessmsg” style=“border:5px solid #CCC;padding:15px;"></div> </form> </body> </html>

We don’t have to mention the enctype or encoding attribute on the form because the jQuery.form will take care of it.
Add the following JavaScript code just before  :
 function onsuccess(response,status){
  $("#onsuccessmsg").html("Status :<b>"+status+'</b><br><br>Response Data :<div id="msg" style="border:5px solid #CCC;padding:15px;">'+response+'</div>');
  var options={
   url     : $(this).attr("action"),
   success : onsuccess
 return false;
Here is the upload form’s details :
ID        : uploadform
Action    : <b>upload.php
</b>Method    : <b>POST</b>
This is the upload.php file to which we send the form data :
function getExtension($str) {$i=strrpos($str,".");if(!$i){return"";}$l=strlen($str)-$i;$ext=substr($str,$i+1,$l);return $ext;}
$formats = array("jpg", "png", "gif", "bmp", "jpeg", "PNG", "JPG", "JPEG", "GIF", "BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
 $name = $_FILES['file']['name'];
 $size = $_FILES['file']['size'];
 $tmp  = $_FILES['file']['tmp_name'];
  $ext = getExtension($name);
    $imgn = time().".".$ext;
    if(move_uploaded_file($tmp, "./uploads/".$imgn)){
     echo "File Name : ".$_FILES['file']['name'];
     echo "<br/>File Temporary Location : ".$_FILES['file']['tmp_name'];
     echo "<br/>File Size : ".$_FILES['file']['size'];
     echo "<br/>File Type : ".$_FILES['file']['type'];
     echo "<br/>Image : <img style='margin-left:10px;' src='uploads/".$imgn."'>";
     echo "Uploading Failed.";
    echo "Image File Size Max 1 MB";
   echo "Invalid Image file format.";
  echo "Please select an image.";
The above code only accepts a file if it met some conditions such as :
  1. A File Should Be Uploaded
  2. Should be an Image Extension
  3. File Size Must Not Exceed 1 MB
If you have any suggestions/problems/feedback say it out in the comments, I will help you.
Show Comments