Tutorialsplane

Ajax Image Upload PHP and jQuery Script Download Demo

Ajax Image Upload PHP and jQuery Script Download Demo : It is very simple to upload an image using jquery & php. In this script are going to use jQuery at client side and PHP at server side to upload an image without reloading or refreshing the page. You can try online demo and download the full script.

Ajax Image Upload PHP and jQuery Script Download Demo

Here are the steps to upload image in php using jquery. Let us go step by step.


Step 1

first create the form to select and upload the image.

Note : For Design we are using bootstrap.css

Create file upload-ajax-image.php

Create Image From

 <div class="col-sm-12"><div id="uploadedimage"></div>
<form role="form"  id="uploadImageForm" enctype= "multipart/form-data"  action="javascript:void(0)" onsubmit="uploadimage(this);">
<div class="form-group">
<label for="file">Select Image</label>
<input type="file" name="uploadImage" class="form-control" id="uploadImage"
placeholder="select file">
</div>
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>


Step 2

Create imageupload.js

Create Js File

function uploadimage(this){
$.ajax({
url: "uploadimageajax.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#uploadedimage").html(data);
}
});
}

Step 3

Create uploadimage.php

Which will upload the posted image by the jquery and ajax and will move in a folder ie. target folder in which you want to store images on the server.

Create upload php file

$target_dir = "uploads/";
$upload = 1;
$target_file = $target_dir . basename($_FILES["uploadImage"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Invalid Format.Only JPG, JPEG, PNG & GIF files are allowed.";
$upload = 0;
exit;
}if ($_FILES["uploadImage"]["size"] > 200000) {
echo "Sorry, your file is very large.";
$upload = 0;

exit;
}
if($upload == '1'){
$str = '';
if (move_uploaded_file($_FILES["uploadImage"]["tmp_name"], $target_file)) {
$str .= "The file ". basename( $_FILES["uploadImage"]["name"]). " has been uploaded.";
$str .= "<img src='uploads/".$_FILES["uploadImage"]["name"]."'>";
} else {
echo "Sorry, there was an error uploading your file.";
}
}

Ajax Image Upload PHP and jQuery Script Download Demo


You can run demo to see the upload functionality online or you can directly download and unzip the file to run the demo on your machine.

DemoDownload

Ajax image upload in php