Triggering event after preventDefault() doesn't work as expected - javascript

$(document).on('click', '[data-toggle="if-exist"]', function (e, options) {
options = options || {};
if (options.fileExist) {
return true;
}
var target = e.currentTarget;
var fileId = $(this).data('file');
e.preventDefault();
$.ajax({
url: Routing.generate('checkFile', {file: fileId }),
type: 'HEAD',
statusCode: {
404: function () {
alert('File does not exist');
},
200: function () {
$(target).trigger('click', { 'fileExist': true });
}
}
});
});
When clicking the button the HEAD request is send and when I've got 200 response than the click event is triggered again but this time with fileExist option. Listener is called again (I checked this) but nothing happens, it's like e.preventDefault() would still working. Any ideas?
Solution
trigger() method will trigger jQuery event, but will not trigger default behaviour for a browser, which in my case is redirecting to another page. This code works:
$(document).on('click', '[data-toggle="if-exist"]', function (e) {
var target = this;
var fileId = $(this).data('file');
e.preventDefault();
$.ajax({
url: Routing.generate('checkFile', { file: fileId }),
type: 'HEAD',
statusCode: {
404: function () {
alert('File does not exist');
},
200: function () {
var event = document.createEvent('MouseEvents');
event.initEvent('click', false, false);
target.dispatchEvent(event);
}
}
});
});

use e.stopImmediatePropagation(); to stop multiple calls of ajax.

Related

How to check a form is submitted or other links are clicked in jquery?

Currently i have a $(window).unload function which do some tasks on leaving that page. but i need these actions to be done only if a form is not submitted. This is what i have done so far`
$(window).unload(function () {
var flag=0;
$("#id-message-form").submit(function(){
flag=1;
});
if(flag!=1){
$.ajax({
url: "app/ajax_handler.php",
type: 'GET',
async: false,
data:{},
beforeSend: function() {
},
complete: function() {
},
success: function(data) {
}
});
}
});`
You could set a flag when a form is submitted - and then check that in your unload function.
// Set this globally
var formSubmit = false;
$('form').on('submit', function() {
formSubmit = true;
}
Then in your window unload function;
if(!formSubmit) {
// your code that submits the form
}
The issue is due to the scope of the flag variable and the submit handler. Place them outside the unload handler. I'd also suggest changing flag to a boolean value.
var formSubmitted = false;
$("#id-message-form").submit(function() {
formSubmitted = true;
});
$(window).unload(function() {
if (!formSubmitted) {
$.ajax({
url: "app/ajax_handler.php",
type: 'GET',
data: {},
async: false,
beforeSend: function() {},
complete: function() {},
success: function(data) {}
});
}
});
The submit() will no matter submit the form by default. You should try click() function to store flag value instead.

How to override the jQuery.ajax success function after it has been initialized?

A button click triggers an ajax request. When the user clicks the button a second time while the first request is still loading, i want to override the first request's success function with another one.
Basically I want to do this:
var ajaxRequest = null;
jQuery('#mybutton').click(function () {
if (ajaxRequest) {
ajaxRequest.success = function () {
};
}
ajaxRequest = jQuery.ajax({
url: '...',
success: function () {
console.debug('do something');
}
});
});
But the initial success handler is been called.
How to achieve an override?
You can try the following hack, I have tested it with asynch setTimeout (instead of asynch jQuery.ajax) and it works -
var mySuccessHander = function() {
console.debug('Initial function');
}
var test = jQuery.ajax({
url: '...',
success: function() {
mySuccessHander();
}
});
And when the button is clicked for the second time, execute following -
mySuccessHander = function() {
console.debug('Overridden function');
}
Nice question , this will work..
var isRequestDone = true;
jQuery('#mybutton').click(function () {
var requestParams = {
url: '....',
beforeSend: function () {
isRequestDone = false;
},
success: function () {
isRequestDone = true;
console.debug('do something');
},
error: function () {
isRequestDone = true;
}
}
if (!isRequestDone) {
requestParams.success = function () {
console.log('please wait for a while!');
};
}
jQuery.ajax(requestParams);
});
beforeSend will fire just before the request will go to server , so when request in on the server isRequestDone will be false and hence will change success handler . on success callback from the first request it will again back to original.
You can set the ajax arguments to a variable first so you can modify it later on.
var clicks = 0,
ajaxArgs = {
url: '...',
success: function () {
console.debug('do something');
}
};
$('#myButton').click(function() {
++clicks;
if (clicks > 1) {
// set the success function if clicked more than once
ajaxArgs.success = function () {
console.debug('Success function ' + clicks);
}
}
$.ajax(ajaxArgs);
});
If you want to modify the success function only when ajax is still loading you can do this:
var loading = false,
ajaxArgs = {
url: '...',
success: function () {
console.debug('do something');
}, complete: function () {
loading = false;
}
};
$('#myButton').click(function() {
if (loading) {
// set the success function if ajax is still loading
ajaxArgs.success = function () {
console.debug('Another Success function ');
}
} else {
loading = true;
$.ajax(ajaxArgs);
}
});

AJAX Unload not firing

I need to run a process when the user exists or leaves a page. I have the following code that I received from another SO question I posted:
<script>
var unloaded = false;
$(window).on('beforeunload', unload);
$(window).on('unload', unload);
function unload() {
if (!unloaded) {
$.ajax({
type: 'post',
async: false,
url: '/Function/Left/#ViewBag.ID',
success: function () {
unloaded = true;
$('body').css('cursor', 'default');
},
timeout: 5000
});
}
}
The problem is that the /Function/Left event is NEVER fired. Is something wrong?

Can't figure out why this ajax request fires two times

I am working on this snippet of code, but I can't figure out why the ajax request is firing up twice when I click the selected button:
$('#passwd-nuova').blur(function() {
var response = $('#passwd-nuova').validate({
'classeform': 'form-utenti',
'empty': 'passwd-nuova'
});
if (!response.empty) {
$('#reset').addClass('btn-disabled');
} else {
$('#reset').removeClass('btn-disabled');
/*
* RESET PASSWORD PANNELLO
*/
$('#reset').on('click', function() {
var new_passwd = $('input[name=passwd-nuova]').val();
var selezionato = $(this).loadID({
'nometabella': 'utenti',
'abbr': 'utenti'
});
var send_email = $('#cb-email').prop('checked');
$.ajax({
cache: false,
type: "POST",
url: "/gutenti/",
dataType: "json",
data: {
'mod-passwd': true,
'idu': selezionato,
'new-passwd': new_passwd,
'send-email': send_email
},
success: function(response) {
var tab = $("#datatable_utenti").dataTable();
$('#modal-reset').modal('hide');
tab.fnDraw();
$(window).scrollTop(0);
$(document).genAlert({
tipo: 'success',
msg: 'modifica completata con successo',
time: 800
});
$('input').each(function() {
$(this).val('');
});
$("#datatable_utenti tbody").compileForm({
'abbr': 'utenti',
'nometabellaDB': 'admin_utenti',
'nometabella': 'utenti'
});
$(document).stato(profile, 'base');
return;
},
error: function() {
console.log("errore async");
$('#modal-reset').modal('hide');
$(window).scrollTop(0);
$(document).genAlert({
tipo: 'error',
msg: 'qualcosa è andato storto, riprova',
time: 800
});
}
});
return;
});
}
});
I've tried to disable the button after the call, and also to return nothing to exit from the function, but nothing has worked.
Your $('#passwd-nuova').blur handler binds the $('#reset').click' handler multiple times.
I'm glad my comment helped you out ;)
I have called the function inside the blur funciton. However; The function is going to be called also when you click the #reset button. I hope it works.
$('#passwd-nuova').blur(function() {
var response = $('#passwd-nuova').validate({
'classeform': 'form-utenti',
'empty': 'passwd-nuova'
});
if (!response.empty) {
$('#reset').addClass('btn-disabled');
} else {
$('#reset').removeClass('btn-disabled');
/*
* RESET PASSWORD PANNELLO
*/
$('#reset').click();
}
});
$('#reset').on('click', function() {
var new_passwd = $('input[name=passwd-nuova]').val();
var selezionato = $(this).loadID({
'nometabella': 'utenti',
'abbr': 'utenti'
});
var send_email = $('#cb-email').prop('checked');
$.ajax({
cache: false,
type: "POST",
url: "/gutenti/",
dataType: "json",
data: {
'mod-passwd': true,
'idu': selezionato,
'new-passwd': new_passwd,
'send-email': send_email
},
success: function(response) {
var tab = $("#datatable_utenti").dataTable();
$('#modal-reset').modal('hide');
tab.fnDraw();
$(window).scrollTop(0);
$(document).genAlert({
tipo: 'success',
msg: 'modifica completata con successo',
time: 800
});
$('input').each(function() {
$(this).val('');
});
$("#datatable_utenti tbody").compileForm({
'abbr': 'utenti',
'nometabellaDB': 'admin_utenti',
'nometabella': 'utenti'
});
$(document).stato(profile, 'base');
return;
},
error: function() {
console.log("errore async");
$('#modal-reset').modal('hide');
$(window).scrollTop(0);
$(document).genAlert({
tipo: 'error',
msg: 'qualcosa è andato storto, riprova',
time: 800
});
}
});
return;
});
I guess that this line:
$('#reset').on('click', function() {
........
runs more than once(on each blur).
You can bind an event more than once with no problem.
Check if this solves your problem:
$('#reset').off('click').on('click',function(){ .....
If it does, then try to move the "event attachment" to a different place.
Jquery - 'on' and 'off'
Try unbind / bind the click callback:
var callback = function () { ... }
$('#reset').unbind('click', callback);
$('#reset').bind('click', callback);
If you attach the click event twice, it will get called two times.

Ajax, prevent multiple request on click

I'm trying to prevent multiple requests when user click on login or register button. This is my code, but it doesn't work. Just the first time works fine, then return false..
$('#do-login').click(function(e) {
e.preventDefault();
if ( $(this).data('requestRunning') ) {
return;
}
$(this).data('requestRunning', true);
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
$(this).data('requestRunning', false);
}
});
});
Any ideas? Thanks!
The problem is here:
complete: function() {
$(this).data('requestRunning', false);
}
this no longer points to the button.
$('#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);
}
});
});
Use on() and off(), that's what they are there for :
$('#do-login').on('click', login);
function login(e) {
e.preventDefault();
var that = $(this);
that.off('click'); // remove handler
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize()
}).done(function(msg) {
// do stuff
}).always(function() {
that.on('click', login); // add handler back after ajax
});
});
In your ajax callbacks the context (this) changes from the outer function, you can set it to be the same by using the context property in $.ajax
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
context: this, //<-----
success: function(msg) {
//stuffs
},
complete: function() {
$(this).data('requestRunning', false);
}
});
You can disable the button.
$(this).prop('disabled', true);
I have also faced a similar problem.
Just adding $('#do-login').attr("disabled", true); gives me the solution.
$('#do-login').click(function(e) {
e.preventDefault();
$('#do-login').attr("disabled", true);
.........
.........
Here do-login is button id.
I've tried this and worked very fine for me, I was having trouble that $.ajax send more request until results return,
var settings = {
"url": "/php/auth/login.php",
"method": "POST",
"timeout": 0,
"async": false,
"headers": {
"Content-Type": "application/json; charset=utf-8"
},
"data": jsondata, //data pass here is in JSON format
};
$.ajax(settings).done(function (ress) {
try{
console.log(ress, "Result from Ajax here");
}
catch(error){
alert(error);
console.log(ress);
}
});
async : false worked for me.
Thanks.
Or you can do it by $(this).addClass("disabled"); to you button or link and after click is performed, you can $(this).removeClass("disabled");.
// CSS
.disabled{
cursor: not-allowed;
}
// JQUERY
$('#do-login').click(function(e) {
e.preventDefault();
$(this).addClass("disabled");
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
context: this,
success: function(msg) {
//do more here
$(this).removeClass("disabled");
},
});
});
P.S. If you use bootstrap css, you do not need the css part.
I found the approach useful. I've implemented it as a general purpose function for jQuery with ES6.
export default function (button, promise) {
const $button = $(button);
const semaphore = 'requestRunning';
if ($button.data(semaphore)) return null;
$button.data(semaphore, true);
return promise().always(() => {
$button.data(semaphore, false);
});
}
Because $.ajax() returns a promise, you simply pass in the promise and the function takes care of the rest.
Roughly speaking, here's the usage.
import preventDoubleClick from './preventdoubleclick';
...
button.click(() => {
preventDoubleClick(this, () => $.ajax()
.done(() => { console.log("success") }));
});
This function can help you with control multi Ajax requests and it's has timeout function which can return flag status to 0 after ex. 10sec (In case the server took more than 10 seconds to respond)
var Request_Controller = function(Request_Name = '', Reactivate_Timeout = 10000)
{
var a = this;
a.Start_Request = function(){
if(window.Requests == undefined){
window.Requests = {};
}
window.Requests[Request_Name] = {'Status' : 1, 'Time': + new Date()};
}
a.End_Request = function(){
if(window.Requests == undefined){
window.Requests = [];
}
window.Requests[Request_Name] = undefined;
}
a.Is_Request_Running = function(){
if(window.Requests == undefined || window.Requests[Request_Name] == undefined){
return 0;
}else{
var Time = + new Date();
// Reactivate the request flag if server take more than 10 sec to respond
if(window.Requests[Request_Name]['Time'] < (Time - Reactivate_Timeout))
{
return 0;
}else{
return 1
}
}
}
}
To use it:
var Request_Flag = new Request_Controller('Your_Request_Name');
if(!Request_Flag.Is_Request_Running()){
Request_Flag.Start_Request();
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
Request_Flag.End_Request();
}
});
}
for prevent multiple ajax request in whole site. For example: If use ajax request in other ajax page, Using ajax in php loop, etc, Give you multiple ajax request with one result. I have solution:
Use window.onload = function() { ... }
instead of
$(document).ready(function(){ ... });
on the main index.php page. Its will be prevent all multi request. :)

Categories