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
Related
the title may be a bit misleading but I'm not sure how to phrase it better, so I apologize for that.
I'm creating a custom handler so the site doesn't refresh when new content is pressed (similar to how youtube works, for example).
For that I'm using this script:
$('.sidebar2 li a').click(function (e) {
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
e.preventDefault();
test = false;
return false;
}
}
});
});
even though I've stated e.preventDefault() to trigger, javascript loads the new content into the current frame without refreshing, but the browser refreshes again anyway.
I've tried to use href="#" however in this case when I go back and handle that, I always end up with two same pages, one without and one with # at the end, and in addition to that it wouldn't be very user friendly to have all links href="#"
What am I doing wrong to make the browser redirect "normally" even though I've told him no no no?
I've also tried adding onclick="javascript:void(0)" on a elements and that didn't help
ajax is async. By the time success callback is called event will already be bubbled up the DOM tree and processed. You need to call preventDefault before sending a request.
$('.sidebar2 li a').click(function (e) {
e.preventDefault(); // here for example
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
test = false;
// returning here makes no sense also
// return false;
}
}
});
});
The code below performs ajax request whenever a link is clicked. It first performs request and then follows the link specified in href. This works fine in Chrome, but in Firefox or Safari, such code doesn't successfully post data for reasons unknown to me. What would be the workaround for these 2 browsers?
$(".submit-link").click(function(e){
var value=$.trim($(".url-submit").val());
if(value.length>0){
//initialize name and email
$.ajax({
url: "getPOST.php",
type: 'POST',
data: {"id":value,"name":nameValue, "email":emailValue},
success: function(response) {
console.log(response); //nothing gets printed in console when using Firefox or Safari, but in Chrome it works as expected
}
//go to link in href now
});
}else{
//do something else
e.preventDefault();
}
});
Just lets make the code more simple;
$(".submit-link").click(function (e) {
e.preventDefault();
var value = $.trim($(".url-submit").val());
if (value.length > 0) {
//initialize name and email
$.ajax({
url: "getPOST.php",
type: 'POST',
data: { "id": value, "name": nameValue, "email": emailValue },
success: function (response) {
console.log(response);
window.location = $('.submit-link').attr('href'); //Assumed your element that has submit-link class also contains the href attribute
}
});
}
});
After you completed your ajax request, now you can go to link.
I added e.preventDefault(); at the start of function. If the value length greater than "0" it will make the ajax request and after the ajax request completed user will be redirected to link.
Also check your value to be sure it has length greater than "0".
I know that this question is asked in many ways, I'm also able to make it work. It only doesn't work in combination with a key* event...
Why doesn't .abort() work in this function?
function setGlobalSearch(){
var xhr;
$('#globalSearch').keyup(function(){
if(xhr && xhr.readystate != 4){
xhr.abort();
}
var searchVal = $(this).val();
xhr = $.ajax({
type: "GET",
url: "/ajax.actions?i=globalSearch&q="+searchVal,
success: function(data) {
$('#globalSearchResults').html(data);
},
dataType:"html",
cache:false
});
});
}
The abort() function will only fire if the request has been sent. I can only suggest that this is possibly not the case.
However, I would recommend a different pattern which negates the need to abort requests, which is, as you've seen, occasionally a little flaky. Instead I would only fire the request once typing has ceased for a set number of milliseconds. Try this:
var timer;
$('#globalSearch').keyup(function() {
clearTimeout(timer);
timer = setTimeout(function() {
var searchVal = $(this).val();
$.ajax({
type: "GET",
url: "/ajax.actions?i=globalSearch&q="+searchVal,
success: function(data) {
$('#globalSearchResults').html(data);
},
dataType:"html",
cache:false
});
}, 150); // fire the AJAX request 150ms after typing stops.
});
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
});
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;
}
}