Upload Image By Ajax Using jQuery FormData Without Submit Form

Image Upload By JQuery Ajax and PHP

File uploading by jQuery Ajax,  PHP, and  HTML it’s a common feature for the dynamic application but sometimes when form submitted page got refresh after clicked submitted button. But if don’t need to refresh the page use jQuery and Ajax for sending form-data to PHP File.  In this blog, I show the simplest way to upload a single image or file using form data and by using JQuery Ajax and PHP.

HTML Code – Input Field for File Upload

Input type file and Button for click button to call function

 <div class="uploadQrImage">
<input type="file" name="imageUploadQr" id="imageUploadQr" />
</div>
<div class="buttonUpload">
<input type="button" onclick="generateImageQr();" value="Generate QR Code" />
</div>

jQuery Ajax Code – Using Form Data

FormData object is used to submit form and file by JQuery Ajax. Basically, formData sent contact form data to the server script which is written in PHP file. Ajax processes the form data and upload the files.

Below code ajax() function used for sending the file upload request by formData.

 
function generateImageQr(){
    var imageId = jQuery('#imageUploadQr').prop('files')[0];
    var formData = new FormData(); 
    formData.append('file',imageId);
    console.log(formData);
    $.ajax({
        url : 'sumbitQr.php',
        type : 'POST',
        data : formData,
        cache : false,
        contentType : false, 
        processData : false, 
        success : function(data){
            console.log(data);
        }
    });   
}

PHP Code – Move Upload file to the folder

Create PHP Code for move uploaded file by input type file jQuery to upload folder.

<?php 
if(isset($_FILES['file'])){
    echo 'Get Uploaded File';   
    if(0 < $_FILES['file']['error']){
        echo $_FILES['file']['error'].'<br>'; 
    }else{
        move_uploaded_file($_FILES['file']['tmp_name'], 'upload/'.$_FILES['file']['name']); 
    }
}   
?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *