image upload in php with ajax

By : PHPErrorCode September 17, 2017 635 Views php,ajax

Hello friends i am going to share with you how to make jquery ajax simple use in image upload without page refresh in your website in Core PHP.

Image upload in php with ajax and jQuery is very important topic nowadays because every person wants to save their data without refreshing the page. Today we are going to generate an Jquery & Ajax based image uploader in your website, which means the image will be uploaded to your website location using Ajax request, without reloading the page. We are using jQuery & Ajax to send image file to the server side core PHP script. We can also use core php $_FILE array element to check file size, image type and check Image exist or not in your website before uploading.

use jQuery & AJAX to implement upload and Show image in your website. In this form add file and text input field and a submit button. On submitting the form with the selected image file and inserted text, the AJAX script will be executed. In this code, in this Tutorial core PHP moves the uploaded image to the target directory and returns the show the preview image list as an AJAX response HTML Data.

We Are Following 4 steps are pointed under this process :

  1. Include jQuery library in header area.
  2. HTML page Desin with upload field.
  3. Create jQuery Ajax code.
  4. Create PHP script page to store and show image.

Step :1 Create HTML Form index.php file

simple HTML form to upload image file, php file to uploaded image to the server side and jquery code to upload image easily without reloading page and to view the uploaded image into the particular table.

<html>
<head>
<title>Image upload in php with ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="script.js" type="text/javascript"></script>
</head>
<body>
  <div class="container" style="background:#F44336;">
      <div class="col-sm-5">
          <h1 class="text-center well">image upload in php with ajax</h1>
          <form class="form-horizontal addForm" id="" action="addData.php" method="post">
              <div class="form-group">
                <label class="control-label col-sm-2" for="email">Name:</label>
                <div class="col-sm-10">
                  <input type="text" class="form-control" id="name" placeholder="Name" name="name">
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-sm-2" for="pwd">Image:</label>
                <div class="col-sm-10">          
                  <input type="file" class="form-control" id="img"  name="image">
                </div>
              </div>
              <div class="form-group">        
                <div class="col-sm-offset-2 col-sm-10">
                  <button type="submit" class="btn btn-default btn_data">Submit</button>
                </div>
              </div>
          </form>
      </div>
      <div class="col-sm-3">
          <h1 class="text-center well">Show Data</h1>
          <table class="table table-bordered" id="show">
            <thead>
              <tr>
                <th>name</th>
                <th>image</th>
              </tr>
            </thead>
            <tbody>
              <?php 
                include('config.php');
                $result = mysqli_query($conn,"SELECT * FROM image ORDER BY ID DESC");

                //check Table record emty or not
                if (mysqli_num_rows($result) > 0) 
                {
                  // output data of each row
                  while($row = mysqli_fetch_assoc($result)) 
                  {
              ?>
              <tr>
                <td><?php echo $row['name']; ?></td>
                <td><img width="100px" src="images/<?php echo $row['image']; ?>"></td>
              </tr>
              <?php } } ?>
            </tbody>
          </table>
      </div>
  </div>
</body>
</html>

Step 2: AJAX Code, Create script.js file

In this code create the ajax() function used to the image upload request by posting the FormData instance. In core PHP, it uploads the image to the specified directory. After successful image upload without page refresh, it will show the uploaded image HTML as the AJAX in response. Then, this will be added to a target Table to show the preview for the post name and image.

In this FormData() is a HTML5 object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data.

$(document).ready(function (e) {
    $(".addForm").on('submit',(function(e) {
        e.preventDefault();
	$.ajax({
        url: "addData.php",
	    type: "POST",
	    data:  new FormData(this),
	    contentType: false,
    	    processData:false,

	    success: function(data)
            {
		$('#show').html(data);
	    },	
	    error: function() 
	    {
                $('#show').html('Error...');
	    } 	        
        });
    }));
});

Step 3: Insert Record In MySQL Database

You need to set the path to stroke the image, such as $ target_dir = "images /"; And this path must be created as well as folders.

Here have to applied some validations on the selected file, to check it whether is an image file or not such as png, jpg, jpeg, bmp and gif.

Upload image size allowed is 2 MB. such as $_FILES["image"]["size"] > 2000000

2000000 = 2 MB

to upload inage in your website derctory and insert the record in your database See the below code

<?php
include('config.php');
$name=$_POST['name'];

if ($_FILES["image"]["tmp_name"] =="") 
{
  if(isset($_POST['id']))
  {
      $id=$_POST['id'];
    $conn->query("UPDATE image SET name=$name WHERE id=$id");
  }
}
else
{

  $target_dir = "images/";
  $filename = explode('.',$_FILES['image']['name']);
  $ext = $filename[1];
  $imgname = time().'.'.$ext;
  $target_file = $target_dir . $imgname ;

  $uploadOk = 1;
  $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    // Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["image"]["tmp_name"]);
    if($check == false) 
    {
      $text="File is not an image.";
      $uploadOk = 0;
    }

    // Check if file already exists
    if (file_exists($target_file)) 
    {
        $text="Sorry, file already exists.";
        $uploadOk = 0;
    }

    // Check file size
    if ($_FILES["image"]["size"] > 2000000) 
    {
        $text="Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" && $imageFileType != "bmp" ) 
    {
        $text = "Sorry, only JPG, JPEG, PNG, GIF & BMP files are allowed.";
        $uploadOk = 0;
    }

  // Check if $uploadOk is set to 0 by an error
  if ($uploadOk == 0) 
  {
    echo $text;
  } 
  else 
  {
      if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) 
      {
          $path=$imgname;

          if(isset($_POST['id']))
      {
        $id=$_POST['id'];
        $conn->query("UPDATE image SET name=$name , image = $path WHERE id=$id");
          }
          else
          {
            $conn->query("INSERT INTO image (name,image)VALUES ('$name','$path')");
          }
      } 
      else 
      {
        echo 'not upload image';
      }
  }
}
  // search for run time view data
  include('serchData.php');
?>

Step 4: search for run time show data create serchData.php file

<thead>
  <tr>
    <th colspan="2">Image Upload Seccess....</th>
  </tr>
  <tr>
    <th>name</th>
    <th>image</th>
  </tr>
</thead>
<tbody>
  <?php 
    $result = mysqli_query($conn,"SELECT * FROM image ORDER BY ID DESC");

    if (mysqli_num_rows($result) > 0) 
    {
      while($row = mysqli_fetch_assoc($result)) 
      {
  ?>
  <tr>
    <td><?php echo $row['name']; ?></td>
    <td><img width="100px" src="images/<?php echo $row['image']; ?>"></td>
  </tr>
  <?php } } ?>
</tbody>