How to Upload Image using jQuery Ajax in PHP?

By Hardik Savani May 14, 2024 Category : PHP Javascript jQuery

Hey Dev,

In this example, you will learn php ajax image upload with preview. This article will give you a simple example of ajax image upload using jquery ajax php. you will learn ajax image upload in php. This article goes in detailed on php ajax image upload example.

In this post i show you how to image upload without page reload using jquery ajax. jquery ajax through you can upload image and store record into database in php. i use jquery.form plugin for image uploading. So you can do by following few step of file uploading ajax jquery.

Preivew


First you have to create index.php file as i do in following file, so create index.php file and put bellow code.

index.php

<html lang="en">

<head>

<title>PHP - Image Uploading with Form JS Example</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>

<script src="http://malsup.github.com/jquery.form.js"></script>

<script>

$(document).ready(function() {

$(".upload-image").click(function(){

$(".form-horizontal").ajaxForm({target: '.preview'}).submit();

});

});

</script>

</head>

<body>

<nav class="navbar navbar-default">

<div class="container-fluid">

<div class="navbar-header">

<a class="navbar-brand" href="#">PHP - Image Uploading with Form JS Example</a>

</div>

</div>

</nav>

<div class="container">

<form action="imageuploadpro.php" enctype="multipart/form-data" class="form-horizontal" method="post">

<div class="preview"></div>

<input type="file" name="image" class="form-control" style="width:30%" />

<button class="btn btn-primary upload-image">Save</button>

</form>

</div>

</body>

</html>


Ok, now create another file for retrive php post request and image uploading code, so create imageuploadpro.php file and put bellow code:


imageuploadpro.php

<?php

define('DB_SERVER', 'localhost');

define('DB_USERNAME', 'root');

define('DB_PASSWORD', 'root');

define('DB_DATABASE', 'learn');

$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);


if(isset($_POST) && !empty($_FILES['image']['name'])){


$name = $_FILES['image']['name'];

list($txt, $ext) = explode(".", $name);

$image_name = time().".".$ext;

$tmp = $_FILES['image']['tmp_name'];


if(move_uploaded_file($tmp, 'upload/'.$image_name)){

mysqli_query($db,"INSERT INTO items (title)

VALUES ('".$image_name."')");

echo "<img width='200px' src='upload/".$image_name."' class='preview'>";

}else{

echo "image uploading failed";

}


}

?>

Now, we are ready to run this script before you have to craete upload folder for store donaloding image file, so first create upload folder and run.

Tags :
Shares