Today, In this tutorial, we will be explaining how to Upload an image without a form submitting using ajax. many people say it is possible to upload an image without a form submitting but it is possible. so let's go we use this tutorial to make possible.

We have used jquery and ajax and in this below file. we have taken also FormData() object.

When the user clicks on button then we will get the image data and it is passed into FormData() object and call the ajax with FormData() object data.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Upload an image without a form submitting using ajax - XpertPhp</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  <script>
	$(document).ready(function(){
		$('#btnUpload').on('click', function() {
			var file_data = $('#fileImage').prop('files')[0];
			var form_data = new FormData();
			form_data.append('file', file_data);

			$.ajax({
					url         : 'upload.php',     
					dataType    : 'text',           
					cache       : false,
					contentType : false,
					processData : false,
					data        : form_data,                         
					type        : 'post',
					success     : function(output){
						if(output=="File Uploaded Successfully")  
						{
							$('.error').html('<div class="alert alert-success"><strong>Success!</strong> '+output+'</div>');
						}
						else if(output=="Only allowed jpeg,jpg and png extension")
						{
							$('.error').html('<div class="alert alert-danger"><strong>Danger!</strong> '+output+'</div>');
						}
						else{
							$('.error').html('<div class="alert alert-danger"><strong>Danger!</strong> '+output+'</div>');
						}
							
					}
			 });                
		});
	});
</script>
</head>
<body>

<div class="container" style="margin-top:25px;">	
  <div class="error"></div>
    <div class="form-group">
		<label for="fileImage">Upload a Image:</label>
		<input id="fileImage" type="file" name="fileImage" />
    </div>
	<button id="btnUpload" class="btn btn-default">Upload</button>
</div>
</body>
</html>

upload.php

When ajax call the upload.php file then the image will be upload into images directory.

<?php
$src = $_FILES['file']['tmp_name'];
$targ = "images/".$_FILES['file']['name'];

$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if(in_array($file_extension, $validextensions))
{	
	if(move_uploaded_file($src, $targ))
	{
		echo "File Uploaded Successfully";
	}
	else
	{
		echo "Failed";
	}
}
else{
	echo "Only allowed jpeg,jpg and png extension";
}

?>