Attach progressbar in existing upload button - php

I have a browse button by which user can browse file upto 100 mb. But the problem is, it is uploading the attch file when user submitting the form. And it is not showing in anywhere that how much file uploaded. I want to show it with a progressbar.
U can visit my site http://historikindia.com/contact_us.php.
Please help me to do it. It is now sending attachment to my email. but i need to show user the progressbar otherwise they may think that it is not responding properly (for large file upload).

Here is the code from ajax uploader which updated a status bar. You need to have an html5 progress bar in your html page for it to work.
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
$('#btnupload').click(function(){
var formData = new FormData(document.getElementById('fileupload'));
$.ajax({
url: 'upload.php', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function (e) { return true; },
success: function (json) { return true; },
error: function (json) { return false; },
// Form data
data: formData,
dataType: "json",
//Options to tell JQuery not to process data or worry about content-type
cache: false,
processData: false
});
});
html5 progress bar looks like this
<progress value="1" max="100"></progress>

Related

Upload multiple files at once to server with Summernote File

What changes, please, can I make to the code below, so that my upload.php file can receive multiple files which I would them loop through to process? I have been trying to upload multiple files at once to server using Summernote. Although, I select multiple files from my laptop for the upload, only one file gets uploaded. I feel certain that the PHP file which handles the upload is not the problem because it receives only one file even if I select multiple files for upload. Below is how the JQuery code looks like
$('.summernote-mini').summernote({
height: 200,
tabsize: 2,
callbacks: {
onFileUpload: function(files) {
callBack(files[0]);
},
}
});
Callback Function
function callBack(files) {
let data = new FormData();
data.append('media_upload[]', files);
$.ajax({
data: data,
type: "POST",
url: "upload.php",
cache: false,
contentType: false,
processData: false,
xhr: function() { //Handle progress upload
let myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
return myXhr;
}
}).done(function(reponse){
//I handle the response here
});
}
Regardless of the number of files I select to upload, count($_FILES['media_upload']['name']) gives me 1 in my e.g upload.php file which handles the server side file upload. What could be the solution to this problem?
After receiving assistance from #Fravadona I got the solution to the problem.
I replaced callBack(files[0]); with callBack(files);as #Fravadona suggested.
Then, in the call back function, I replaced data.append('media_upload[]', files); with the code below:
var iLength = files.length;
var i;
for(i = 0; i < iLength; i++){
data.append("media_upload[]", files[i]);
}
So the correct code has become this:
$('.summernote-mini').summernote({
height: 200,
tabsize: 2,
callbacks: {
onFileUpload: function(files) {
callBack(files);
},
}
});
And the call back function has become this:
function callBack(files) {
let data = new FormData();
var iLength = files.length;
var i;
for(i = 0; i < iLength; i++){
data.append("media_upload[]", files[i]);
}
$.ajax({
data: data,
type: "POST",
url: "upload.php",
cache: false,
contentType: false,
processData: false,
xhr: function() { //Handle progress upload
let myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
return myXhr;
}
}).done(function(reponse){
//I handle the response here
});
}
So now, I am able to successfully upload multiple files at once using Summmernote.

Jquery Image Source Change is not Working

I am Trying to change user image through ajax by overwriting existing image file with new one so how can i show user image without reloading the page.
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
// $("#message").empty();
// $('#loading').show();
alert('i m clicked');
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
// $('#loading').hide();
$('#previewing').hide();
// $("#message").html(data);
// $('PreviewImage').attr("src","<?php echo $ImageSource; ?>");
var img = $("#PreviewImage");
img.attr("src","<?php echo $ImageSource; ?>");
// alert(data);
}
});
}));
As per #Deepak comment i have concatenate the timestamp with image source to show new image.
if your image is not getting refreshed add time string after image url like
$timestamp = time(); img.attr("src","<?php echo $ImageSource.'?'.$timestamp;");

How to fetch file type data (image) on JQuery page and send to PHP page for image upload

I want to upload an image using jQuery asynchronously with data... but cannot upload it... Only data variables can be fetch there in process page but cannot get the image file using $_FILES......
img_upload.php
<form name="frm" id="frm" novalidate enctype="multipart/form-data">
<input type="text" id="txt_name" name="txt_name" />
<input type="file" name="img_upload" id="img_upload">
</form>
img_upload.js
$(function() {
$("#frm_edit input, #frm_edit textarea").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
var txt_name = $("input#txt_name").val();
var FileImgData = $('#img_upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', FileImgData);
$.ajax({
url: "./img_upload_p.php",
type: "POST",
data: {
txt_name: txt_name,
upload_photo: FileImgData
},
cache: false,
})
},
});
});
img_upload_p.php
$str_name="";
if(isset($_POST["txt_name"])) { $str_name=trim($_POST["txt_name"]); }
$str_upload_photo="";
if(isset($_FILES['file_photo']))
{ $str_upload_photo = trim($_FILES['file_photo']['name']); }
Please suggest me that image variable declared (upload_photo: FileImgData) in JQuery file "img_upload_p.js" is correct or not.
Also, the way image file variable is fetched in "img_upload_p.php" is correct or not.
if any of them are wrong then how can I assign that image variable in JQuery file and fetch in PHP process page...
PHP image upload code is ready and in working condition... but just having issue with above two mentioned points...
img_upload.js
$(function() {
$("#frm_edit input, #frm_edit textarea").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
var formData = new FormData();
formData.append("hdn_pkid", $("input#hdn_pkid").val()); // if hidden variable is passed
formData.append("txt_name",$("input#txt_name").val()); // if other input types are passed like textbox, textarea, select etc...
formData.append('img_upload', $('input[type=file]')[0].files[0]); // if image or other file is passed
$.ajax({
url: "./img_upload_p.php",
type: "POST",
data: formData,
contentType: false,
processData: false,
cache: false,
})
},
});
});
img_upload_p.php
Get all variables' value using POST method and store them in new variables to use and process on this page as usual.
Get file variable like below mentioned code and then upload image using normal PHP function or your own way.
if(isset($_FILES['img_upload']))
{ $str_ = trim($_FILES['img_upload']['name']); }
One of the best way to do this is use Dropzone js, this is a best library for uploading files using ajax and it also provides progress bar. You can use your own PHP(or any other server side language) code at server side.
I hope it will helpful.

Return data from webserver with ajax

I use this code to upload file with ajax.
$('form').submit(function(e) {
e.preventDefault();
var fd = new FormData(this);
$.ajax({url: $(this).attr('action'),
xhr: function() { // custom xhr (is the best)
var xhr = new XMLHttpRequest();
//load
xhr.upload.addEventListener("load", function(evt) {
$("#msg").text(evt.target.responseText);
}, false);
return xhr;
},
type: 'post',
processData: false,
contentType: false,
data: fd,
success: function(data) {
// do something...
}});
});
I want to display a message in the #msg div when the upload is complete. The message is printed server side using php. Normally evt.target.responseText contains the data from the server, but it contains [object XMLHttpRequestProgressEvent] (which in turn gets written to #msg). I tried printing evt.responseText and evt.response but both also return [object XMLHttpRequestProgressEvent].
Move the line to the "success" callback function block.
An AJAX request call, or its underlying XMLHttpRequestObject (XHR) call is executed asynchronously. The "load" is a Level 3 event that notifies the calling script the progress of the execution. The evt object can be interrogated for use cases such as a file uploader progressbar.
The "success" event is mapped to readyState==4, which is checked by the onreadystatechange callback function.
Using raw XHR:
xhr = new XMLHttpRequest();
xhr.open('GET', your_url, true);
xhr.onreadystatechange=function(){
if (xhr.readyState==4){
document.getElementById('res').innerHTML=xhr.responseText;
} else {
document.getElementById('res').innerHTML='loading...';
}
}
xhr.send(null);
Realistically you can just display the loading text before the XHR call.
Tracking file uploading progress is different:
xhr.upload.onprogress=function(e){
if (e.lengthComputable)
document.getElementById('res').innerHTML=Math.round(e.loaded*100/e.total)+'%';
else document.getElementById('res').innerHTML='uploading...';
};
xhr.onload=function(e){
//display success message
}
Make sure that xhr.upload is not null. If it is, then you don't have Level 3 AJAX support on the browser.

How can I upload a file using jquery's $.ajax function with json and php

I am trying to upload a file using jQuery's $.ajax function but didn't get any output.
Somebody please help me to solve this.
I don't know if this script is correct.
My script is:
$.ajax({
url:'newsup.php',
data: "",
type: 'POST',
contentType:'multipart/form-data',
dataType: 'json',
catche: 'false',
success:function(data6)
{
$("#disp").removeClass().addClass((data6.error=== false)? 'success':'error').html(data6.msg).fadeIn('fast');
//dele();
if($("#disp").hasClass('success'))
{
alert("success");
setTimeout("$('#disp').fadeOut('slow')",3000);
}
},
error:function(XMLHttpRequest,textStatus,errorThrown)
{
$("#disp").removeClass().addClass('error').html("There was an <strong>"+errorThrown+"</strong> error due to <strong>"+textStatus+" condition").fadeIn('fast');
}
});
Also I need help getting data from file uploading field using jQuery.
Please use plugin for this.In my opinion this plugin is better solution for this.You don't need to remember all options etc.Just replace your 'ajax' to 'ajaxForm'.
Please read examples ,below
http://jquery.malsup.com/form/#ajaxForm
This is how I've done it. Use the FormData object.
Note: The odd syntax of the for statement is just setting "f" to the array[i] instance.
$("#submit").click(function () {
var formData = new FormData();
for (var i = 0, f; f = fileArray[i]; i++) {
formData.append("opmlFile", f);
}
$.ajax({
url: "/Documents/SaveFiles/" + #Model,
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false
})
.error(function (xhr, status, error) {
$.notify(error, true);
})
.success(function (data, status, xhr) {
$.notify("Success");
});
});
Unfortunately I don't recall which article I got this from, but it was someone else on Stack Overflow.
AJAX doesnt support file uploading. There are plugins like ajaxfileupload which basically creates a hidden form and uploads your file dynamically.
take a look here and read Oli's answer
I'm using this and it's working fine:
$('#btnUploadFile').on('click', function () {
var data = new FormData();
var files = $("#fileUpload").get(0).files;
// Add the uploaded file content to the form data collection
if (files.length > 0) {
data.append("upload", files[0]);
}
// Make Ajax request with the contentType = false, and procesDate = false
var ajaxRequest = $.ajax({
type: "POST",
url: "/api/documents",
contentType: false,
processData: false,
data: data,
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
console.log(data);
}
});
ajaxRequest.done(function (xhr, textStatus) {
$("#response").attr('class', "alert alert-success");
$("#response").html("File uploaded successfully");
});
});
You can use either of the two plugins Jquery File Upload Plugins 1 or Jquery File Upload Plugins 2 and there's no errors on this script.
Hope it helps
Thanks,
Rashid
Ajax supports File upload using FormData Object, Also supports in all major browser except IE8/9
See below
https://developer.mozilla.org/en-US/docs/Web/API/FormData
Another option would be to base64 encode the file contents and send it as a string, decoding it at the back-end.
Simply use submit event on form to send the files and prevent default form action
$('#form').submit(function(e) { return false; });
and get the file on the server side via
$_FILES['inputName'];

Categories