Ajax request monitoring flow - javascript

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();

Related

jQuery's "uploadProgress" not firing in "$.ajax"

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
}
});

Avoid multiplication of ajax request

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.

Implement SSE (Server Sent Events) with File Upload to ASHX Handler

I want to implement the following:
Call an ASHX hanlder from UI using Jquery.
Upload a file to this ASHX handler.
And when upload is complete, I want to keep sending messages from the server to UI (SSE) to tell the user about the execution status of the code in ASHX handler.
I am stuck with the 3rd point that has been mentioned above.
Following is the UI code that I have written:
var file = $("input#importFileInputHidden")[0].files[0];
var formData = new FormData();
formData.append('file', file);
importAjaxCall = $.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
$('#progressBar').show();
//Method to show the progress of the file being uploaded
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round((evt.loaded / evt.total) * 100);
$('#percentageImportComplete').text('' + percentComplete + '%');
$('#importStatus').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
type: 'post',
url: "Handler.ashx",
data: formData,
processData: false,
contentType: false,
success: function (data) {
//Some code to show success status to user
});
How to capture the messages I am sending from the server?
Have to tried to look into responseText property of http request?
success: function () {
console.log(xhr.responseText);
});

jQuery, ajax .done fired late?

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

How to pass a javascript variable to php without opening a new page

I have a user enter a value in a form and onClick() activates a function that takes the URL the user pasted and cuts it down (using an algorithm I made, but that is irrelevant). I end up with a string of 11 characters and im not sure how to get this to a php page that submits it to my database. The way i am doing it now takes the browser to a new page and i want the user to stay on the same page.
function findvideoid(){
window.location.href = 'submitvid.php?videoID=' + videoID;
}
Pure JavaScript solution (recommended):
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyStatus == 4) { // finished
if (xhr.status == 200) { // 200 HTTP code returned by server
}
else { // error
}
}
};
xhr.open("GET", "your-script.php?videoID=" + encodeURIComponent(videoID));
xhr.send(null);
jQuery solution (recommended if you already use jQuery in your project or if you want to try it out):
// PHP script can access $_GET['videoID']
jQuery.get("your-script.php?videoID=" + encodeURIComponent(videoID));
// PHP script can access $_POST['videoID']
jQuery.post("your-script.php", {videoID: videoID});
jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
What about masking the actual ajax call with the loading of an external html resource?
If no real callback is expected, you could inject an iframe into the document pointing to the specified url and then remove it from the document.
Here's an example of accessing your backend's api url masked by loading an image:
function findvideoid(id, callback){
var img = new Image();
img.onload = callback;
img.src = apiUrl + '?videoId=' + encodeURIComponent(id)
+ '&antiCache=' + new Date().getTime();
}
No ajax. No other libs. Google does it for it's analytics. Why shouldn't you?
Use AJAX:
function findvideoid()
{
var html = $.ajax({
type: "POST",
url: "submitvid.php",
data: "videoID=" + videoID,
async: false
}).responseText;
if(html == "success")
{
// Uncomment the following line in your application
//return true;
}
else
{
return false;
}
}
You can do this easily in jQuery
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});

Categories