Yii, ajax, Button. How to prevent multiple JS onclick bindings

(First of all, English is not my native language, sorry if I'm probably mistaken). I created a Yii web application, where the input form is on the main page, which appears after clicking the button through an ajax request. The form has a Cancel button that makes the div with an invisible form. If I click "Show form" and "Cancel" N times, and then submit the form with the data, the request repeats N times. Obviously, the browser binds the event onclickto the submit button each time the form appears. Can someone explain how to prevent this? Thank!

+3
source share
6 answers

I had the same problem, and this was discussed in the Yii Forum .

This mainly happens because you are likely returning ajax results using "render ()" or renderPartial (). This adds javascript code every time to activate all ajax buttons. If they were already active, they will be activated twice. So the solution is to use renderPartial (). Either use rendering only the first time, and then renderPartial (), or use renderPartial () from the beginning, but make sure that processOutput is only set to TRUE for the first time.

+3
source

! : . JS- CHtml:: ajaxSubmitButton , onclick . ! . , , "", 'click'. submit. , ! :

echo CHtml::submitButton($diary->isNewRecord ? '' : '', array('id' => 'newRecSubmit'));
Yii::app()->clientScript->registerScript('btnNewRec', "
    var clickNewRec = function()
    {
        jQuery.ajax({
            'success': function(data) {
                $('#ui-tabs-1').empty();
                $('#ui-tabs-1').append(data);
            },
            'type': 'POST',
            'url': '".$this->createUrl('/diary/newRecord')."',
            'cache': false,
            'data': jQuery(this).parents('form').serialize()
        });

        $('#new-rec-form').unbind();

        return false;
    }

    $('#newRecSubmit').unbind('click').click(clickNewRec);
");

, -.

+2

, , beforeSend. jQuery undelegate() , .

<?php echo CHtml::ajaxSubmitButton(
  $model->isNewRecord ? 'Add week(s)' : 'Save',
  array('buckets/create/'.$other['id'].'/'.$other['type']),
  array(
    'update'=>'#addWeek',
    'type'=>'POST',
    'dataType'=>'json',
    'beforeSend'=>'function(){$("body").undelegate("#addWeeksAjax","click");}',
    'success'=>'js:function(data) {
      var a=[];
     }',
  ),
  array('id'=>'addWeeksAjax')
); ?>

'addWeeksAjax' , Yii, jQuery undelegate().

+1

, , : "id" ajax ( smth

                <?=CHtml::ajaxLink('<i class="icon-trash"></i>',
                    $this->createUrl('afisha/DeletePlaceAjax',
                    array('id'=>$value['id'])),
                    array('update'=>'.data', 
                     'beforeSend' => 'function(){$(".table").addClass("loading");}',
                     'complete' => 'function(){$(".table").removeClass("loading");}'),
                   array('confirm'=>"?",'id'=>md5($value['id']).time()))
                     ?>

). , renderPartial "processOutput" = true. , js-.

0

-, jQuery.on. . : (, , ). :

<div id="img_35" class='img-layer'>
   <img src='path.jpg'>
   <button class='view' ... />
   <button class='edit' ... />
   <button class='delete' ... />
</div>

JS ( delete, ):

<script type="text/javascript">
    $(document).on('click', '.img-layer .delete', function() {
        var imgId = String($(this).parent().attr('id)).split('_')[1]; //obtain img ID
        $.ajax({
           url: 'http://www.some.ajax/url',
           type : 'POST',
           data: {
               id: imgId
           }
        }).done({
            alert('Success!');
        }).fail({
            alert('fail :(');
        });
    }
</script>

, . , . .

, -.


,

0
source

Source: https://habr.com/ru/post/1793001/


All Articles