PHP Image upload without refreshing page using jquery example

By Hardik Savani | March 4, 2016 | | 62245 Viewer | Category : PHP Javascript jQuery


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.



Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.