Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alertify is executing before confirmation?

I decided to modify and style i little bit my code with Alertify. My old code :

<script type="text/javascript">
$('.ask').click(function(){
    var answer = confirm('<?php echo $this->translate('Delete route?'); ?>');   
    return answer;
});

When I press ok a php script runs and deletes the record. Javascript return true or false.

The problem I have with Alertify is that I even cant press ok or cancel, my php script runs before that. Here is the code:

$(".ask").click(function(event){
alertify.confirm("Are you sure you want to commit your reservation?", function (e) {
    if (e) {
        return true; 
    } else {
        return false;
    }
});

});

I saw some people with similar problems and I saw that I need to use prevent defaults (it makes sense) The code:

$(".ask").click(function(event){
event.preventDefault(); // cancel submit
alertify.confirm("Are you sure you want to commit your reservation?", function (e) {
    if (e) {
        return true; // submit form skipping jQuery bound handler
    } else {

    }
});

});

In that case the php script doesnt run before i press ok/cancel but it doesnt run too when i press one of the buttons. Nothing happens. Any help please ?

like image 563
Lubomir Borisov Avatar asked Sep 18 '14 09:09

Lubomir Borisov


1 Answers

You're running into the asynchronous nature of JavaScript. In the original code, execution of all JavaScript is paused while the confirm dialog is open, so you can directly use the return value from it. However, when you use alertify.confirm, it doesn't pause execution of the script, so the click handler returns immediately and any code around it will also run - ie the code to invoke your php script. When you attempt to return true; from inside the alertify.confirm callback function, you're returning from that inner function to the alertify code, not returning from your outer click handler function.

What you need to do is start to work with the callback methods available, rather than against it - I would suggest restructuring your code as follows. Following confirmation that .ask is an a tag, the following should work:

$(".ask").click(function(event){
  var loc = $(this).attr('href');
  alertify.confirm("Are you sure you want to commit your reservation?", function (e) {
    if (e) {
        document.location.href = loc;
    }
  });
  //prevent link from being followed immediately on click
  return false;
});
like image 197
James Thorpe Avatar answered Oct 20 '22 08:10

James Thorpe