I have a little problem with my functions.
When I execute a function which launchs an Ajax call several times, each time, it multiplicate the number of call.
For example, I want to send a commentary, the first time, all is going good. But if I want to send another, it will be send twice. And if I do it again, it will be send three times.
If you can help me, it will be great :D
Thanks in advance.
Javascript:
$('.modifier').live('click',function(e){
e.preventDefault();
$('#error').hide();
var form = document.querySelector('form')
var formdata = new FormData(form);
formdata.append('fichier', window.file[0]);
//console.log(window.file[0]);
$('input[name=titre]').val('');
$('input[name=fichier]').val('');
$('textarea[name=description]').val('');
window.request_upload = $.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('.chargement').show();
$('.chargement> #progress_bar').css({'width' : percentComplete*100 + '%'}).text(Math.round(percentComplete*100) + '%');
//console.log(percentComplete);
}
}, false);
return xhr;
},
url: "foobar.php",
type: "POST",
data: formdata,
async: true ,
cache: false,
contentType: false,
processData: false
})
.done(function(data){
var json = $.parseJSON(data);
//console.log('Data : '+data);
//console.log('L\'erreur : '+json.erreur);
if(json.erreur == 0)
{
//console.log(json.titre);
var titre = json.titre;
$.notify('Votre photo : "'+titre+'" a bien été envoyé !',{autoHideDelay: 10000, className: 'success'});
$('.drop_depot').removeClass('hover');
$('.chargement').hide();
$(this).removeClass('hover');
$('.drop_depot').empty().append('<span>'+options.message+'</span>');
$('.drop_depot').css({'width': '30%', 'height': '100px' });
$(window).resize();
$('input[type=file]').val('');
}
else{
$('.chargement').hide();
$('#error').show().after(json.erreur + ' ' + json.erreurs);
}
});
}
});
I load this script by : $.getScript() function. If it can help ...
I got the solution.
My problem come from the multiple execution of $.getScript() function.
But I could do this to solve it :
if(!$("body").data(script_bool))
{
$.getScript(script);
$("body").data(script_bool, true);
}
The script_bool variable is the name of the script called.
If it can help someone.
Related
I am new to jQuery and now, I am currently working on file uploads. And I want to add some progress bar each time I upload image. I used the uploadProgress in jQuery but it seems doesn't work. Here's my code:
$('#_form_').on('submit', function(e){
var file_and_desc = new FormData($(this)[0]),
form_url = "_pages/_form_";
var ext = choose.val(),
allowed = ['jpg','png'];
if(ext){
var get_ext = ext.split('.');
get_ext.reverse();
if($.inArray(get_ext[0].toLowerCase(), allowed) > -1){
//upload image
$.ajax({
url : form_url,
type: 'POST',
data: file_and_desc,
contentType: false,
processData: false,
uploadProgress: function(event, positio, total, percentComplete){
$('h1').html(percentComplete);
},
success: function(data){
// some code here...
}
});
}
}
});
That's it! What should I do?
According to the $.ajax() reference, uploadProgress is not a valid option.
Instead, the xhr option is used instead, which lets you set progress listeners on the XMLHttpRequest that is used by the ajax request.
this answer shows how to do that:
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
//Do something with upload progress here
}
}, false);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data){
//Do something on success
}
});
I have an ajax request, whereby I am installing a magento shop automatically, and when the process is done, it would redirect the user to the newly created shop. Here are my codes:
function postSuccessFormData() {
var targetUrl = '/index.php/install/wizard/successPost';
jQuery('.form-button').addClass('loading');
setInterval(installStatus(),4000);
jQuery.ajax({
url: targetUrl,
global: false,
type: 'POST',
data: ({
finish: 1,
password_key: jQuery('#password_key').val()
}),
async: true,
dataType: 'json',
error: function() {
alert("An error has occurred. Please try again.");
},
success: function(data) {
window.location.href = '/';
}
});
function installStatus() {
var installerUpdatesUrl = '/index.php/install/wizard/installerStatus';
//showProgressBar();
jQuery.ajax({
url: installerUpdatesUrl,
// global: false,
type: 'GET',
async: true,
dataType: 'json',
error: function (data) {
// alert(data.result);
},
success: function (data) {
handle data.result
var dataKeys = Object.keys(data);
var lastElementKey = dataKeys[dataKeys.length - 1];
var lastMessage = data[lastElementKey]['message'];
if(data[lastElementKey]['progress'] == '') {
updateProgressBar(data[dataKeys[dataKeys.length - 2]]['progress'],100);
}
setting message
jQuery("#message").html(lastMessage);
if (data[lastElementKey]['state'] == 'Failure') {
var stepStr = lastElementKey.split('_');
var stepString = stepStr[0].toUpperCase() + ' ' + stepStr[1] + ':';
alert(stepString + "\n" + data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
return false;
} else if (data[lastElementKey]['state'] == 'Finish') {
alert(data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
//window.location.href = '/';
} else {
// installStatus();
}
},
complete: function () {
installStatus();
jQuery('.form-button').removeClass('loading');
}
});
}
The way this is done:
After every 4 seconds the function installStatus is run, which will output the current progress in JSON format. My problem is, this function needs to be executed simultaneously with the function post().
This is not happening, the installStatus is only run after the first function has been completed.
What is wrong?
You are executing installStatus when you define it. So this:
setInterval(installStatus(),4000);
needs to be
setInterval(installStatus, 4000);
The new XMLHttpRequest has a nice progress event you can listen to show the user the upload progress.
Here's the spec with a nice demo: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
Initially you should call installStatus() only once and then inside the method inside ajax success you should update the procent in the progress bar and call it recursively the same method. On the server side you can save the current procent in a cookie and with every recursive call you can update the cookie and return the procent.
I have an image upload feature that works like this:
$('.update-insertimage-form').submit(function() {
$(".submit-newupdate-btn").addClass('disabled');
var rootAsset = $('.rootAsset').html();
var formData = new FormData($('.update-insertimage-form')[0]);
$.ajax({
url: rootAsset+'saveUploadedImage',
type: 'post',
cache: false,
dataType: 'json',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
$(".form-control-addupdate").append('<div class="uploading-overlay">Uploading Image...</div>');
$(".uploading-overlay").fadeIn();
},
success: function(data) {
$(".submit-newupdate-btn").removeClass('disabled');
if(data.errors) {
$('.modal-body').append('<div class="alert alert-danger centre-text modal-error-message" role="alert"><strong>Error!</strong> '+ data.errors +'</div>');
} else if (data.success) {
$(".form-control-addupdate").append('<img class="temp_added_image" src="/public_html/user_uploads/build_images/'+data.name+'.jpeg"><br><br>');
$(".uploading-overlay").fadeOut(function(){
$(".uploading-overlay").remove();
});
var $t = $('.form-control-addupdate');
$t.animate({"scrollTop": $('.form-control-addupdate')[0].scrollHeight}, "slow");
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
Instead of just 'Uploading Image' I want to show the user a percentage or a loading bar etc. I have searched around but cannot find much information. My thoughts so far are tracking when the ajax call is made and then when the success call back is returned. But no idea how to generate a loading percentage etc.
I would rather use a percentage number as apposed to a loading bar, and it can be a 'fake' number just so long as it increases and finishes at 100% when the image is uploaded.
Thanks!
EDIT: Just to make it clear, I dont need a specific and real percentage. Just a way of increasing from 1 - 100% from the point the call is made to it being received.
You'll want to include the xhr option in the AJAX request and add an Event Listener to track the progress of the request:
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener('progress', function(e) {
$('.progressbar .bar').css('width', '' + (100 * e.loaded / e.total) + '%');
$('.progresspercent').text((100 * e.loaded / e.total) + '%');
});
return xhr;
},
Where progressbar and progresspercent are elements in your HTML
did anyone have an idea why the:
success, complete and done
event fired 5-10 seconds later than the "xhr.upload.addEventListener("load")" event?
What is the correct event?
iam not shure, which time the correct upload-time is?
hope, that somebody can help me :)
greets
paD
$('body').on('change', '#fileUploader', function() {
// Post-Daten vorbereiten
//var data = new FormData();
//data.append('file', this.files[0]);
var xhr = new XMLHttpRequest();
var data = new FormData();
var files = $("#fileUploader").get(0).files;
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
// Ajax-Call
$.ajax({
url: '<?=$this->language->modulLink('Upload/DoUpload');?>',
data: data,
type: 'POST',
cache: false,
processData: false,
contentType: false,
success: function() {
console.log("JETZT");
},
complete: function(){
console.log( "action finished" );
},
xhr: function() {
var xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete + ' :: ' + evt.loaded + ' :: ' + evt.total);
//Do something with upload progress here
}
}, false);
xhr.upload.addEventListener("load", function(evt) {
console.log("rdy");
}, false);
return xhr;
},
}).done(function(d) { console.log(d); });
});
It's because you are making AJAX call which is asynchronous. Ajax sends the Request from the client side and without waiting for the response starts executing the code statements written(in your case event listener) after the AJAX call code statement. Then once it receives the response from server, based on the response it executes either the success/failure method.
(1.) Ajax call is sent
-->
(2.) Statements after the AJAX call (i.e eventlistener method) are executed
-->
(3.) Server finally responds to AJAX call
-->
(4.) Success method of AJAX call is executed
I recommend you to go through this tutorials. AJAX
I have an AJAX Request in a JavaScript script where I GET a file like that:
$.ajax({
type: "GET",
url: "./" + img_type + ".bmp",
dataType: "html",
timeout: test_timeout,
cache: false,
success: function(msg)
{
//some stuff
}
});
The code itself is correct and works perfectly.
Is there a way to know HOW much of the file I've downloaded while the request is still ongoing?
I mean, once the request gives to me the success message I know that I've downloaded the entire file, but what if I want to know after two seconds of beginning?
Check out the "monitoring progress" section here:
https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
Here's an example:
var xhr = new XMLHttpRequest;
xhr.onprogress = function(e){
if(e.lengthComputable){
var progress = e.position || e.loaded;
var total = e.totalSize || e.total;
var percent = progress/total*100;
//do something with progress here
}
};
xhr.onload = function(){
var content = xhr.responseText;
//do something with the result here
};
xhr.open('GET','./'+type+'.bmp',true);
xhr.send();