In this tutorial, we are going to learn how to upload images using ajax without form in PHP using vanilla javascript. I will guide you through step wise step process on how to upload the image file using pure javascript and not mixed with any jquery or any other.
We are just going to use pure javascript. We are also going to have a progress bar to check if the image has been successfully uploaded.
As bootstrap makes it easy to develop a form without having to keep much effort. I will use bootstrap 4 CDN and integrate it into this sample project to quickly create the form to get started.
Let’s get started and develop features that can upload images using ajax without form.
Create the file structure as shown in the image below:-
How to Upload Image Using Ajax Without Form
What are we going to do?
- Prepare Elegant HTML form quickly and easily using bootstrap.
- Uploading an image with javascript with Ajax and PHP.
Making the design Ready
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" /> <div class="container mt-5"> <div class="offset-2 col-md-6"> <div class="card"> <div class="card-header">File Upload Example With Progressbar - CodeInHouse.com</div> <div class="card-body"> <div class="custom-file"> <input type="file" name="image_file" class="custom-file-input" id="customFile" onchange="onSetFilename(this)"> <label class="custom-file-label" id="custom-file-label" for="customFile">Choose file</label> </div> <div class="progress mt-3"> <div id="progressBar" class="progress-bar progress-bar-striped bg-success" role="progressbar" style="width: 0%" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div> </div> <button type="button" onclick="uploadFile()" class="btn btn-warning text-white mt-2">Upload File</button> </div> </div> </div> </div> |
Uploading an image with javascript with Ajax and PHP.
Add the javascript functions to update the selected image file into the selected box and Ajax code to make requests to the server and send over the image asynchronously.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<script> function onSetFilename(data) { let fileName = data.value.split("\\").pop(); document.getElementById("custom-file-label").innerText=fileName; document.getElementById("progressBar").style.width="0%"; document.getElementById("progressBar").classList.add("bg-success"); } function uploadFile() { const image_files = document.getElementById('customFile').files; if(image_files.length) { let formData = new FormData(); formData.append('image', image_files[0]); let xhr = new XMLHttpRequest(); xhr.open("POST", 'upload.php', true); xhr.addEventListener("progress", function (e) { if(e.lengthComputable) { let percentComplete = e.loaded / e.total * 100; document.getElementById("progressBar").style.width=percentComplete + '%'; } }, false); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { const data = JSON.parse(this.responseText); if(data.success === 1) { document.getElementById("progressBar").classList.remove("bg-success"); document.getElementById("progressBar").classList.add("bg-danger"); alert("Image Uploading failed. Try again..") } } }; xhr.send(formData); } else { alert("No image selected"); } } </script> |
As we have sent our image file into the server now, we have to write some code in PHP to grab the image file process and upload it to our server.
upload.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php function uploadImage($array_name, $imageName, $path) { if (move_uploaded_file($_FILES[$array_name]['tmp_name'], $path . $imageName)) { echo json_encode(['success' => 1]); return (true); } else { echo json_encode(['success' => 0]); return (false); } } if ($_FILES['image']['name'] != '') { $image = $_FILES['image']['name']; uploadImage('image', $image, 'images/'); } |
Finally, your file will be uploaded into your root
directory inside the /image
folder. If you have any other problem regarding uploading images without using form submit in PHP with ajax you can contact us via the contact form on our website. Glad to help.
Leave a Reply