JS measuring the ajax completion time - javascript

I have a simple ajax request for js and php (fetching data from mysql)
function ajax_function(a,b) {
$.ajax({
type : 'POST',
url : mine.ajax_url,
dataType : 'json',
data : {
action : a,
},
success : b
});
};
How would I detect the time that it takes from the initial request to the completion? (I am trying to show progress bar).
Thanks!

If you want progress status:
xhr: function () {
var xhr = $.ajaxSettings.xhr(); // call the original function
xhr.addEventListener('progress', function (e) {
if (e.lengthComputable) {
var percentComplete = e.loaded / e.total;
// Do something with download progress
}
}, false);
return xhr;
}

Related

How to abort ajax request on page refresh

I have a form, on submit of that I am making an ajax request which is sometimes taking time to get the request, so what I am trying to do is whenever user refresh or clicks back button of the browser after form submitting i want to abort that ajax call
What I am doing is
$("#formId").submit(function(event) {
event.preventDefault();
var xhr = $.ajax({
url : "Drilldown",
method : "GET",
success : function(data) {
// here doing ,my stuff
},
complete : function() {
$('.loader').hide();
$('.overlay').hide();
}
});
window.onbeforeunload = function() {
return "some message"; // here when user clicks on leave then want to abort like `xhr.abort`
};
});
whenever the user clicks on leave I want to abort my ajax request
How can I do that?
**I specifically want to do that when ever form submit and once form is submitted,i want to abort that function also onbeforeunload **
You can directly xhr.abort() in "onbeforeunload" event handler method:
// Define xhr variable outside so all functions can have access to it
var xhr = null;
$("#formId").submit(function(event) {
event.preventDefault();
xhr = $.ajax({
url: "Drilldown",
method: "GET",
success: function(data) {
// here doing ,my stuff
},
complete: function() {
$('.loader').hide();
$('.overlay').hide();
}
});
});
window.onbeforeunload = onUnload;
function onUnload() {
if(xhr) xhr.abort();
return "some message";
};
call below method to abort ajax call
xhr.abort()

How to restrict multiple user logins at same time using JavaScript / jQuery

I have developed an ASP.NET MVC Application using JavaScript, jQuery.
I have implemented to be restrict multiple user logins at same time using onbeforeunload/beforeunloadevent.
It works fine, but sometimes not working in onbeforeunload/beforeunloadevent.
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function (e) { // For >=IE7, Chrome, Firefox
if (!validNavigation)
{
$.ajax({
url: '#Url.Action("ClearSession", "Account")',
type: 'Post',
data: "",
dataType: "json",
success: function (data)
{
console.log("onbeforeunload Success")
},
error: function (data) {
console.log("onbeforeunload Error")
}
});
}
return null;
});
There is one also function in AJAX - jQuery is called complete: function(){};
This function checks weather request is running for same user id and password on browser or not, Like this here
complete: function() {
$(this).data('requestRunning', false);
}
Whole AJAX-jQuery implementation here see and implement accordingly, I hope it will work fine for you
Code Here
$('#do-login').click(function(e) {
var me = $(this);
e.preventDefault();
if ( me.data('requestRunning') ) {
return;
}
me.data('requestRunning', true);
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
me.data('requestRunning', false);
}
});
});
See this me.data('requestRunning', false); if it will get any request running for same user id and password it returns false and cancel login.
For more help see here link Duplicate, Ajax prevent multiple request on click
This is not perfect solution but you can implement like this

jQuery File Upload with custom Progress event and Ajax GC

I've built into an app a File Upload with Progress bar using jQuery.ajax .
But I'm concerned that I don't understand how garbage collection will handle it and therefore how memory efficient it will be.
For the progress bar, I had to add a custom xhr in order to add a "progress" event.
When will that custom xhr function and 'progress' event handler be cleaned up?
myApp.prototype.uploadFile = function () {
$.ajax({
type : "POST",
url : posturl,
xhr : function () { // custom xhr
var myXhr = $.ajaxSettings.xhr();
this.onSaveProgress(myXhr, file);
return myXhr;
}.bind(this),
contentType: false,
processData: false,
data : postdata,
beforeSend : this.onBeforeSend,
success : this.onSaveSuccess,
error : this.onSaveError
});
},
myApp.prototype.onSaveProgress = function (xhr, file) {
if (!xhr.upload)
return;
xhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
var percent = Math.floor((e.loaded / e.total)*100) + "%";
$("#progress" + file.id).css("width", percent).text(percent);
}
}, false); // add new progress event handler
}
As you can see, I needed access to the file Object in the 'progress' event handler so I can update the correct progress bar.

Jquery ajax equivalent Titanium

This is an example of how I currently make an api call using titanium:
var url = "http://www.appcelerator.com";
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("Received text: " + this.responseText);
alert('success');
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
// Prepare the connection.
client.open("GET", url);
// Send the request.
client.send();
The trouble is by doing it this way, I am only able to access the object in the onload call back function.
I can't for example do this:
//snippet
var someObject;
onerror : function(e) {
someObject = this.responseText;
},
//end
function useObject(someObject){
alert(someObject);
}
Using jquery AJAX I would be able to do this, like this:
$.ajax({
type: "POST",
url: 'someurl',
data: param = "",
contentType: "application/json; charset=utf-8",
success: self.useObject,
error: errorFunc
});
Once the response is received, pass it to the success object.
How can I do the equilent in Titanium, given that it does not use Jquery.
I don't fully understand what you are trying to achieve ,but try something like:
var onLoad = function(e) {
console.log(this.responseText);
};
var client = Ti.Network.createHTTPClient({
onload: onLoad
});

Stopping an $.ajax call on page unload

I have a procedure running on a timeout to load data in the background:
(function getSubPage() {
setTimeout(function() {
if (cnt++ < pagelist.length) {
loadSubPage(pagelist[cnt]);
getSubPage();
}
}, 500);
})();
In loadSubPage() I'm making $.ajax() calls:
function loadSubPage(page) {
if (typeof(initSubPages[page]) === "undefined") {
$.ajax({
type: "POST",
url: '/Main/GetPageData',
data: { page: page },
success: function (returndata) {
// ...
},
error: function() {
alert("Error retrieving page data.");
}
});
initSubPages[page] = true;
}
}
The problem I'm having is that the error handler is being hit when the user navigates away if any ajax requests are open. I'm trying to get around this by .stop()ing the requests on window.onbeforeunload, but I'm not sure what object to call .stop() on?
jQuery exposes the XMLHttpRequest object's abort method so you can call it and cancel the request. You would need to store the open request into a variable and call abort().
activeRequest = $.ajax({...
and to stop it
activeRequest.abort()
Abort Ajax requests using jQuery
This should come in handy.. You have a jQuery method for doing just that.
The $.ajax returns XMLHTTPRequestObject which has .abort function. This function will halt the request before it completes.
var xhr = $.ajax({ /*...*/
..
..
/* Later somewhere you want to stop*/
xhr.abort();
Read more: How to cancel/abort jQuery AJAX request?
Here is the solution I used based on the feedback:
window.onbeforeunload = function() {
for (page in ajaxing) {
if (ajaxing[page] != null)
ajaxing[page].abort();
}
};
var ajaxing = {};
function loadSubPage(page) {
if (typeof(initSubPages[page]) === "undefined") {
var ajaxRequest = $.ajax({
type: "POST",
url: '/Main/GetPageData',
data: { page: page },
success: function (returndata) {
// ...
},
error: function() {
alert("Error retrieving page data.");
},
complete: function() {
ajaxing[lot] = null;
}
});
ajaxing[page] = ajaxRequest;
initSubPages[page] = true;
}
}

Categories

Resources