Ajax Upload Multiple Images without form submitting

Today, We want to share with you Ajax Upload Multiple Images without form submitting.In this post we will show you PHP Ajax Multiple Image Upload with Preview Example, hear for Uploading files/image with Ajax & Jquery, without submitting a form we will give you demo and example for implement.In this post, we will learn about Ajax Image Upload using PHP and jQuery Example Without Page Refresh with Validation with an example.

Ajax Upload Multiple Images without form submitting

There are the Following The simple About Ajax Upload Multiple Images without form submitting Full Information With Example and source code.

As I will cover this Post with live Working example to develop How to upload a file in Ajax without using a form in PHP, so the some Upload Multiple Images Using PHP and jQuery for this example is following below.

Also Read :  Laravel controller Get csrf tokens in ajax calls

Example 1: Jquery Ajax Uploading image without submitting a form

HTML Part

<input id="profile" type="file" name="profile" />
<button id="upload" value="Upload" />

jQuery Part
$(document).on("click", "#upload", function() {
	var file_data = $("#profile").prop("files")[0];   
	var profile_form_data = new FormData();                
	profile_form_data.append("file", file_data)            
	profile_form_data.append("user_name", "jaydeep Gondaliya")                 
	$.ajax({
                url: "/members_profile_avatar",
                dataType: 'script',
                cache: false,
                contentType: false,
                processData: false,
                data: profile_form_data,                         
                type: 'post'
       })
})

Example 2: Ajax Multiple Image upload using jQuery and PHP

index.php

<div id="fupload">
 <h2>Ajax Image upload - PHP Mysql</h2>
<form action="upload.php" method="post" enctype="multipart/form-data" name="fileupload" id="fileupload">
<input onchange="fileread(this)" name="memberprofilename[]" id="memberprofilename" type="file" multiple />
<input type="submit" id="submit" value="Upload" />
</form>
<div id="profile_uploaded_status">
<div id="progressbar" class='progress'></div><div id="status"></div></div>
<div id="profile_complete"></div>
<div id="imgThumbals"></div>
<div id="error"></div>
</div>

custom.js

function fileread(file) {
var fsize = file.files[0].size;
var fileimgName = file.files[0].name;
var fileimgtype = file.files[0].type;
 var fileimgArr = ["image/png", "image/jpeg", "image/gif", "image/jpg"];
 var fileTrue = fileimgArr.indexOf(fileimgtype);
if(fileTrue>=0){
 var reader = new FileReader();
 reader.element = $(file).parent().find('imgThumbals');
 reader.onload = function(e) {
 var div = document.getElementById("imgThumbals");
 div.innerHTML = "<img class='imgThumbals' src='" + e.target.result + "'" +
 "title='" + fileimgName + "'/>";

var formData = new FormData();
 for (var i = 0; i < file.files.length; i++) {
 var fileup = file.files[i];
 if (!fileup.type.match('image.*')) {
 continue;
 }
 // Add the file to the request.
 formData.append('memberprofilename[]', fileup, fileup.name);

}
 fileImgUpload(formData)
 };
 reader.onerror = function(e) {
	alert("error: " + e.target.error.code);
 };
 reader.readAsDataURL(file.files[0]);
 }else{
 document.getElementById("error").innerHTML = "<span id="IL_AD5" class="IL_AD">Incorrect</span> file format, Please select an image file format..";
}
 }


 function fileImgUpload(formData){
 var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function () {
 if (xhr.status === 200) {
 //console.log(xhr.responseText);
 } else {
 alert('An error occurred!');
 }
};

xhr.upload.addEventListener("progress", profile_imgprogress, false);
xhr.addEventListener("load", Completed, false);
xhr.addEventListener("error", failstatus, false);
 xhr.addEventListener("abort", Abortedstatus, false);
xhr.send(formData);

}

 function profile_imgprogress(event){
 document.getElementById('profile_complete').style.display = 'none';
document.getElementById('profile_uploaded_status').style.display = 'block';

 var percent = (event.loaded / event.total) * 100;
 document.getElementById("status").value = Math.round(percent);
 $("#progressbar").progressbar({value: document.getElementById("status").value});
 document.getElementById("status").innerHTML = Math.round(percent)+"%";
}

upload.php

<?php
if(isset($_FILES['memberprofilename']))
{
 $uploadImgDestination = dirname(__FILE__).'/upload/';
 if(!isset($_FILES['memberprofilename']) || !is_uploaded_file($_FILES['memberprofilename']['tmp_name'][0]))
 {
 die('Sorry, Something went wrong with Upload!');
 }
 $RandomNum = rand(0, 9999999999);

 $fileimgNm = str_replace(' ','-',strtolower($_FILES['memberprofilename']['name'][0]));
 $ImageType = $_FILES['memberprofilename']['type'][0];

 $profileFileExt = substr($fileimgNm, strrpos($fileimgNm, '.'));
 $profileFileExt = str_replace('.','',$profileFileExt);

 $fileimgNm = preg_replace("/\.[^.\s]{3,4}$/", "", $fileimgNm);

 $profileName = $fileimgNm.'-'.$RandomNum.'.'.$profileFileExt;

 move_uploaded_file($_FILES['memberprofilename']['tmp_name'][0], "$uploadImgDestination/$profileName");

 $base_path="http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
 $base=$base_path.'/'.'upload/'.$profileName;
 //echo '<img src="'.$base.'">';
 echo "<div id='sucess' class='paakinfo sucess' > Your Profile Successfully uploaded.</div>";
 }
?>

Angular 6 CRUD Operations Application Tutorials

Read :

Also Read :  Toggle Switches Laravel, Ajax and jQuery example

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Ajax Upload Multiple Images without form submitting.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Gondaliya Jaydeep

Hi, I’m Jaydeep Gondaliya, PHP developer.Pakainfo.com is the most popular Programming & Web Development blog. Our mission is to provide the best online resources on programming and web development.Any visitors of this site are free to browse our tutorials, live demos, Examples and download scripts.If you have a project that you want to get started, launch quickly, contact me. Email : [email protected]

Leave a Reply

  • (will not be published)