Подтверждение Javascript, запуск формы, даже если отменен - PullRequest
0 голосов
/ 18 октября 2018

Итак, у меня есть обработчик формы ajax, который удаляет способ оплаты.Когда пользователь нажимает «удалить», отображается всплывающее окно с подтверждением.Однако, даже если пользователь нажимает кнопку «отменить», он все равно запускает форму и удаляет способ оплаты.Что мне нужно изменить?

HTML:

<form class="sg-inline-form" method="post" action="">
  <input type="hidden" name="sg_customer_id" value="customerID">
  <input type="hidden" name="sg_card_id" value="cardID">
  <a href="#" class="delete-card" onclick="return confirm('Are you sure?')">Delete</a>
</form>

AJAX:

$('.delete-card').click(function() {
    $('.ajax-loading').show();
    const $form = $(this).parent();
    const customer = $form.find('input[name=sg_customer_id]').val();
    const card = $form.find('input[name=sg_card_id]').val();
    $.ajax({
        url: sg_obj.ajaxurl,
        data: {
            'action': 'sg_delete_payment_source',
            'customer' : customer,
            'card' : card
        },
        success:function(data) {
            // This outputs the result of the ajax request
          $('.ajax-loading').hide();
          $('#ajax-messages').addClass('alert alert-success').html('The payment source has been deleted. <a href=".">Refresh Page</a>');
        },
        error: function(errorThrown){
          $('.ajax-loading').hide();
          $('#ajax-messages').addClass('alert alert-danger').html('An error occurred.');
        }
    });  
    });

Ответы [ 3 ]

0 голосов
/ 18 октября 2018

Не делайте две отдельные привязки onClick.Вы можете выполнять свои функции, изменяя свой код следующим образом

HTML:

<form class="sg-inline-form" method="post" action="">
  <input type="hidden" name="sg_customer_id" value="customerID">
  <input type="hidden" name="sg_card_id" value="cardID">
  <a href="#" class="delete-card">Delete</a>
</form>

AJAX:

$('.delete-card').click(function() {
    if(confirm('Are you sure?')) {
        $('.ajax-loading').show();
        const $form = $(this).parent();
        const customer = $form.find('input[name=sg_customer_id]').val();
        const card = $form.find('input[name=sg_card_id]').val();
        $.ajax({
            url: sg_obj.ajaxurl,
            data: {
                'action': 'sg_delete_payment_source',
                'customer' : customer,
                'card' : card
            },
            success:function(data) {
                // This outputs the result of the ajax request
              $('.ajax-loading').hide();
              $('#ajax-messages').addClass('alert alert-success').html('The payment source has been deleted. <a href=".">Refresh Page</a>');
            },
            error: function(errorThrown){
              $('.ajax-loading').hide();
              $('#ajax-messages').addClass('alert alert-danger').html('An error occurred.');
            }
        });
    }
});
0 голосов
/ 18 октября 2018

Это потому, что вы используете прослушивание событий onclick и .click.Вы можете поместить подтверждение в случае остановки пользователя, нажав «Отмена».

$(function(){
  $("#continues").click(
    function(){
      alert("FIRES EITHER WAY");
  });
  
  $("#stops").click(function(){
    if(confirm("TEST")){
      alert("CONTINUED");
    } else {
      alert("STOPED");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="continues" href="#" onclick="return confirm('Continues')">Continues</a>
<a id="stops" href="#">Stops</a>
0 голосов
/ 18 октября 2018

У вас нет условия для проверки того, что на самом деле говорит подтверждение (). эта ссылка показывает, как получить действительный ответ confirm(), и вы должны проверить, был ли ответ истинным или ложным, прежде чем отправлять запрос $.ajax

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...