最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - The script works only once by clicking on the opening and closing

programmeradmin3浏览0评论

What is wrong with my code? What needs to be fixed so that the script always works on clicks of buttons?

<script type="text/javascript">
// Выполнить асинхронный Ajax-запрос с помощью метода POST.
// Отправить данные на сервер и в случае успеха вывести 
// ответ сервера в диалоговом окне.
jQuery(document).die('click', '.sale_buton')  
jQuery(document).on('click', '.sale_buton', function(event) {
jQuery.ajax({
                    url: '/wp-admin/admin-ajax.php', // сделали запрос 
                    type: "POST", // указали метод
                    data: { // передаем параметры отправляемого запроса
                        action: 'my_ajax_action', // вызываем хук который обработает наш ajax запрос
                        price: jQuery(this).data('price'), // передаем параметры из кнопки 
                        user: jQuery(this).data('user'), // передаем параметры из кнопки 
                    },
   success: function(data){
     jQuery('.results').html( /*"ИНФОРМАЦИЯ О СРАЖЕНИИ:<br>" + */data );
}
 })
return false;
/* as before */ });

jQuery(document).on('click', '.close', function() { 
jQuery('.results').remove();
return false;
/* as before */ });

</script>

What is wrong with my code? What needs to be fixed so that the script always works on clicks of buttons?

<script type="text/javascript">
// Выполнить асинхронный Ajax-запрос с помощью метода POST.
// Отправить данные на сервер и в случае успеха вывести 
// ответ сервера в диалоговом окне.
jQuery(document).die('click', '.sale_buton')  
jQuery(document).on('click', '.sale_buton', function(event) {
jQuery.ajax({
                    url: '/wp-admin/admin-ajax.php', // сделали запрос 
                    type: "POST", // указали метод
                    data: { // передаем параметры отправляемого запроса
                        action: 'my_ajax_action', // вызываем хук который обработает наш ajax запрос
                        price: jQuery(this).data('price'), // передаем параметры из кнопки 
                        user: jQuery(this).data('user'), // передаем параметры из кнопки 
                    },
   success: function(data){
     jQuery('.results').html( /*"ИНФОРМАЦИЯ О СРАЖЕНИИ:<br>" + */data );
}
 })
return false;
/* as before */ });

jQuery(document).on('click', '.close', function() { 
jQuery('.results').remove();
return false;
/* as before */ });

</script>
Share Improve this question asked Dec 29, 2019 at 8:16 Василий МаркинВасилий Маркин 417 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

In general, here is my solution code:

<script type="text/javascript">
    // Выполнить асинхронный Ajax-запрос с помощью метода POST.
    // Отправить данные на сервер и в случае успеха вывести 
    // ответ сервера в диалоговом окне.
    //jQuery(document).die('click', '#order_'+button.id) ; 

    function showPopup (button) {
        jQuery(document).on('click', '#'+button.id, function(event) {
        jQuery.ajax({
                            url: '/wp-admin/admin-ajax.php', // сделали запрос 
                            type: "POST", // указали метод
                            data: { // передаем параметры отправляемого запроса
                                action: 'my_ajax_action', // вызываем хук который обработает наш ajax запрос
                                orderid: jQuery(this).data('orderid'), // передаем параметры из кнопки 
                                user: jQuery(this).data('user'), // передаем параметры из кнопки 
                            },
           success: function(data)

           {
             jQuery('.results').html( /*"ИНФОРМАЦИЯ О СРАЖЕНИИ:<br>" + */data );
             jQuery('.results').show();
          }
         })
        return false;
         /* as before */ 
        });
    };
     function closePopup (button_id) {

    jQuery(document).on('click', '#close_'+button_id, function() { 
    jQuery('.results').hide();
    return false;
    /* as before */ });
    }
    </script>

And here is this piece of code in the front-end (this is just part of the code in php file - sorry, but I can’t show the whole file):

    echo '<td style="text-align: center;border-left: none;font-size: 17px;"><button onclick="javascript:showPopup(this);" class="sale_buton checkout-button button alt wc-forward" id="order_'.$lineItem['order_id'].'" data-orderid="'.$lineItem['order_id'].'" data-user="'.$user_id.'" data-variation="'.$lineItem['variation_id'].'" href="">Сразиться</button></td></tr>';// /*'. esc_url( $order->get_view_order_url() ) .'*/Кнопка отрабатывает по клику - выхватывает Ajax-ом такие данные как (id участника-заявителя, название заявки, id заявки, ставка-взнос-тариф)'</td>';     
        } 
    }         
    echo '</tbody></table></br>' ;
    ?>
<div class="results"></div> <!-- здесь будет выводится результат -->

And this is part of the code that I put into the function.php file in the plugin (I also can’t show the code - only the part that is responsible for working with JS):

add_action("wp_ajax_my_ajax_action", "k_ajax_my_ajax_action");// для фронтенда 
add_action("wp_ajax_nopriv_my_ajax_action", "k_ajax_my_ajax_action");// для админки


function k_ajax_my_ajax_action(){
echo '<div class="clos">';
echo '<div class="close" id="close_'.$_POST['orderid'].'" onclick="javascript:closePopup('.$_POST['orderid'].');">Закрыть</div></br>';
//here is some code that can be executed
echo '</div>';
echo '<div class="cl"></div>';
exit; 

}

And CSS:

    .cl {
        width: 100%;
        height: 100%;
        position: fixed;
        top: 1px;
        left: 1px;
        background: black;
        opacity: 0.8;
        z-index: 1030;
    }

    .clos {
        width: 360px;
        height: auto;
        background: white;
        top: 80px;
        z-index: 1031;
        padding: 1%;
        position: fixed;
        left: 50%;
        margin-left: -180px;
    }
.close{
float:right;
font-size:21px;
font-weight:700;
line-height:1;
color:#000;
text-shadow:0 1px 0 #fff;opacity:.2;
filter:alpha(opacity=20)
}
      .close:hover,.close:focus{
color:#000;
text-decoration:none;
cursor:pointer;
opacity:.5;
filter:alpha(opacity=50)
}
      button.close{
padding:0;
cursor:pointer;
background:0 0;
border:0;-webkit-appearance:none
}

And here is a living example: svary.club

发布评论

评论列表(0)

  1. 暂无评论