AdSense

 Upload image without using Form submit button in jQuery AJAX PHP MYSQL


Hello Guys, In this post, we will discuss one of the Ajax-based topics, namely how to upload files or images without using the Submit button Ajax Request Form and PHP scripts without refreshing the page. to upload an image, we first select an image. When we have an image selected, it will be uploaded to the specified location and also insert image name in database. Because we use events to change the query in the file element of the input type.


We use the FormData() object to send the selected image to the server. With the FormData() object, we send the selected image to the server using an Ajax request. With the FormData() Object and Ajax we pass the selected files to a PHP script. With PHP Script we can upload the selected file or image to the server without refreshing the page.


After we upload the selected image, we also upload the image to the web page without refreshing the page. So this is our simple tutorial on how to upload images without using a submission form in Ajax PHP and insert image or file in database display it on web page.


Output

Upload image without using Form submit button in jQuery AJAX PHP MYSQL

See Also


Database Connection 

dbConfig.php
<?php
	// Database configuration 
	$dbHost     = "localhost"; 
	$dbUsername = "root"; 
	$dbPassword = ""; 
	$dbName     = "blog_database"; 
	 
	// Create database connection 
	$con = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 
	 
	// Check connection 
	if ($con->connect_error) { 
	    die("Connection failed: " . $con->connect_error); 
	} 
?>


Create HTML Code for Upload File 

index.php
<html lang="en">
<head>
  <title>Upload image without using Form submit button in jQuery AJAX PHP MYSQL</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>

<div class="jumbotron text-center">
  <h2><b>Upload image without using Form submit button in jQuery AJAX PHP MYSQL</b></h2>
</div>

<div class="container">
  <div class="row">
    <div class="col-md-3"></div>
      <div class="col-md-6">
       <form id="submitForm">
        <div class="form-group">
          <div class="custom-file mb-3">
            <input type="file" class="custom-file-input" name="image" id="image">
            <label class="custom-file-label" for="image">Choose Image to Upload</label>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- view of uploaded images -->
<div class="row">
   <div class="col-md-4"></div>  
      <div class="card col-md-4" id="preview" style="display: none;">
      <div class="card-body" id="imageView">
               
      </div>
   </div>    
</div>

</body>
</html>


jQuery AJAX Code 

<script type="text/javascript">
$(document).ready(function(){
   $("#submitForm").on("change", function(){
      var formData = new FormData(this);
      $.ajax({
         url  : "upload.php",
         type : "POST",
         cache: false,
         contentType : false, // you can also use multipart/form-data replace of false
         processData: false,
         data: formData,
         success:function(response){
          $("#preview").show();
          $("#imageView").html(response);
          $("#image").val('');
          alert("Image uploaded Successfully");
         }
      });
   });
});
</script>


Upload File using PHP MySQL Code

upload.php

<?php
	
	// Include database connectivity
	
	include_once('dbConfig.php');
	
	// upload file using move_uploaded_file function in php
	
	if (!empty($_FILES['image']['name'])) {

	    $fileName = $_FILES['image']['name'];
		
	    $fileExt = explode('.', $fileName);
	    $fileActExt = strtolower(end($fileExt));
	    $allowImg = array('png','jpeg','jpg');
	    $fileNew = rand() . "." . $fileActExt;  // rand function create the rand number 
	    $filePath = 'uploads/'.$fileNew; 

	if (in_array($fileActExt, $allowImg)) {
	    if ($_FILES['image']['size'] > 0  && $_FILES['image']['error']==0) {
		$query = "INSERT INTO table_images (images) VALUES('$fileNew')";
	        if ($con->query($query)) {
		    move_uploaded_file($_FILES['image']['tmp_name'], $filePath);
    		    echo '<img src="'.$filePath.'" style="width:320px; height:300px;"/>';
	        }else{
		    return false;
	        }	
	      }else{
	        return false;
	    }
	}else{	
    	    return false;
	}
    }

?>

You can always support by sharing on social media or recommending my blog to your friends and colleagues.   
If you have any suggestions / problems about this tutorial, please comment on the  form below.😊

Post a Comment

Previous Post Next Post