progress bar tracking with PHP and JQuery - php

I have a form which allow to upload a file in AJAX. It works well, and my progress bar as well. I have 2 questions about my code :
1st : how can i make it compatible with IE 10-
2nd : There is a way to keep the progress when i'm leaving the page ? At time, my progress bar is completing well, but if i leave and return to the page, the progress bar is empty. I would like to keep the progress (eg: my progress bar shows 30%, i leave and return the page after a while, it now shows 55%) ?
My code :
$('#submitfile').click(function(event){
event.preventDefault();
var formData = new FormData($('#form-import-file')[0]);
$.ajax({
url: '{{ path('el_go_to_upload_files') }}',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
}
});
// My progress handler
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}

Related

uploading multiple images on ajax cross domain

I am uploading multiple images cross domain using Ajax and php.
I have set the loader before the Ajax call
Everything works good but when i select multiple images to upload the loader comes after big time delay.
Below is my code
$('#load-div').css('display', 'block');
var data = new FormData();
var c = 0;
var files = new Array();
$.each($('#file')[c].files, function(i, file) {
data.append('files'+i, file);
c++;
});
var other_data = $('#frmaddproperty').serializeArray();
$.each(other_data, function(key, input){
data.append(input.name, input.value);
});
$.ajax({
type: 'POST',
url: 'Coss domain url',
crossDomain: true,
async: false,
cache: false,
contentType: false,
processData: false,
data:data,
success: function(response){
console.log(response);
window.location = 'property_list.php?msg='+response;
},
error: function(){
//alert('Error while request..');
},
});
Above is my code i have set loader in Div id load-div.
it comes after very big delay of time when i upload multiple images.
Don't know what to do about it.
Thanks in Advance.
You can use "ajaxStart()".
https://api.jquery.com/ajaxStart/
It will start the loader when your call starts.
$( document ).ajaxStart(function() {
$('#load-div').css('display', 'block');
});
UPDATE
You can also use, "beforeSend".
$.ajax({
url: '',
beforeSend: function() {
$('#load-div').css('display', 'block');
},
Read more about your options:
http://api.jquery.com/jquery.ajax/
UPDATE
I guess it's this loop that is making the delay.
Try putting the loader inside of it.
Or else you need to give us more code, to figure out what's making the delay!
$.each($('#file')[c].files, function(i, file) {
$('#load-div').css('display', 'block');
data.append('files'+i, file);
c++;
});
async: false,
I have removed this line from my ajax call and loader is working fine.
what it is stands for i don't know

Successive AJAX calls add an extra consecutive call

I have a pretty standard ajax call for a live update, however, say I call the the ajax, everything is good, but say I want to call it again, this time, I will get 2 calls, and if I try again then I'll have 3, I can verify this by invoking and alert and with the Network DevCon of Chrome, any idea why this is happening?
P.S: I'm using Laravel 5.1
$('button[name=act]').click(function() {
var icon = $(this).closest('div.thumbnail').find('i');
$(document).ajaxStart(function() {
icon.show();
});
$("form").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr) {
$(icon).fadeIn(function() {
$(this).removeClass('fa-spinner fa-spin').addClass('fa-check text-success').fadeOut(1000, function() {
$(this).removeClass('fa-check text-success').addClass('fa-spinner fa-spin');
});
});
}/*,
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}*/
});
});
});
The problem is that every time you click on the act button you call $("form").submit(), which adds anothersubmithandler to the form. So if you click on theact` button 3 times, and then click on the form's submit button, it will send 3 AJAX requests.
It's almost always wrong to bind one event handler inside another event handler, you should bind all the event handlers at top level.
var icon;
$(document).ajaxStart(function() {
if (icon) {
icon.show();
}
});
$('button[name=act]').click(function() {
icon = $(this).closest('div.thumbnail').find('i');
});
$("form").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr) {
if (icon) {
icon.fadeIn(function() {
$(this).removeClass('fa-spinner fa-spin').addClass('fa-check text-success').fadeOut(1000, function() {
$(this).removeClass('fa-check text-success').addClass('fa-spinner fa-spin');
});
});
}
}/*,
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}*/
});
});
The reason this is happening is because you are rebinding the submit event function every time the button is clicked which results in multiple copies of the function. Just move it out of the click even, and if you want to force a submit on a click, you can call the submit() function with no parameters to fire the event.
Try the following:
$(function(){
$('button[name=act]').click(function(){
var icon = $(this).closest('div.thumbnail').find('i');
$(document).ajaxStart(function()
{
icon.show();
});
$("form").submit(); //This submits the form on click
});
//This binds the function, so it should only be called once.
$("form").submit(function (e)
{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr)
{
//BLAH
}
});
});
});
I noticed two other things you might want to address. You want to somehow update the icon after it is loaded. You will need to have some other way to find the icon inside of the success function (possibly looking at the data that came back could yield some information that could be useful. Since it is json, it should be easy to update.)
Also, the way you currently have it will bind to all forms on the page. In the event that you have multiple forms on the page, you will probably want to change the selector to use an id.
Hope this helps!
Based in incremental calls and my guessings, I have to say that you're printing this code each time you make the (ajax) call, leading to bind your form element again in each call..
Am I right?
JO.

PHP is only passing FILE name to my script

I am working on building some AJAX video upload functionaliyy on my CMS, and ended up implementing the solution which was awarded the bounty here as it best suited my purposes (cross browser compatibility isn't an issue as I will only ever be managing my site via Chrome).
I've been experiencing some extremely strange behavior when I submit my form, when I var dump - the contents of my $_FILES array only includes the name parameter
The jQuery I use to submit to my upload file is as follows:
$('#confirm').click(function(){
var file = new FormData($('form')[0]);
$.ajax({
url: './app/core/commands/upload.php',
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var 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
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
},
// Form data
data: file,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
Any ideas as to why my $_FILE array is empty?? I am baffled.

How to upload file using jquery ajax php

I have a file uploading system using jquery's formdata
the thing goes like this --->
HTML
<form id="upload-form" method="post" enctype="multipart/form-data" action="resource/php/upload.php">
<input style="display:none;" type="file" id="upload" multiple>
</form>
JQUERY
$('#upload').change(function(e){
var formdata = new FormData(),file;
$('#ajax-loader').show(); //simple gif loader
for(var i=0;i<this.files.length;i++){
file = this.files[i];
var ftype = file.type;
formdata.append("files[]", file);
}
if (formdata) {
$.ajax({
url: "resource/php/upload.php",
type: "POST",
data: formdata,
dataType : 'json',
processData: false,
contentType: false,
success: function(data) {
$('#ajax-loader').hide();
//appends the currently uploaded images in a div
}
});
}
});
PHP
//does lot of stuff
// echo's out 2 arrays in json format which is used in appending images as stated earlier^
echo json_encode(array("images"=>$db_image_id,"src"=>$db_image_src));
Now my question is when i am choosing files to upload it automatically using #upload an #ajax-loader is shown and hidden when files are uploaded. But i want to show a progress bar in percentage and ETA(time left) replacing the simple $('#ajax-loader') . However I googled and was able to do that using ajax-form a jQuery Plugin. But i want to do in more real terms i dont want to use any PLUGINS. How will i do that ?
And one more question is whether using the #upload-form is that necesssary ?
You need to write custome xhr function to achieve tracking of progress of file uploads
$.ajax({
url: "resource/php/upload.php",
type: "POST",
data: formdata,
dataType : 'json',
processData: false,
contentType: false,
//#custome xhr
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;
},
//#custome xhr end
success: function(data) {
$('#ajax-loader').hide();
//appends the currently uploaded images in a div
}
});
See the comment #custome xhr in above code And add a function to update progress bar
function updateProgress(evt) {
console.log('updateProgress');
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
} else {
// Unable to compute progress information since the total size is unknown
console.log('unable to complete');
}
}
Ref: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest

Displaying progress bar upto response occur using jquery ajax submission

I am send request to PHP page by using jquery ajax concept, I have to display the response in dialog box. It works fine but the problem is it takes time to get response. So can I add progress bar to it.
$.ajax({
type: "POST",
url: "push/push_notify.php",
data: "pushmessage="+message+"&iphone="+iphone+"&android="+android+"&blackberry="+blackberry,
success: function(e){
var response = e;
apprise(response, {'animate':true});
}
});
return false;
You could show some spinner image before running the request and hide it after the request finishes, i the complete handler. For example:
$('#spinner').show();
$.ajax({
type: "POST",
url: "push/push_notify.php",
complete: function() {
$('#spinner').hide();
},
data: {
pushmessage: message,
iphone: iphone,
android: android,
blackberry: blackberry
},
success: function(e) {
var response = e;
apprise(response, {'animate':true});
}
});
And here's a site for some AJAX spinners.

Categories