Home Javascript PHP Image upload without refreshing page using jquery

PHP Image upload without refreshing page using jquery

by Shahriar Sagor

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

So at first we need to create index.php file as we do in following file, so need to create index.php file and then put bellow code.


<html lang="en">
<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> 
        $(document).ready(function() { 
            	$(".form-horizontal").ajaxForm({target: '.preview'}).submit();
	<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 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>

Ok good , now need to create another file for as retrive php post request and image uploading code, so need to create imageuploadpro.php file and just put the bellow code:


define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_DATABASE', 'learn');

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'>";
		echo "image uploading failed";


Read Also :Laravel Join with Subquery in Query Builder Example

Thanks for read. I hope it help you. For more you can follow us onĀ facebook.


You may also like