I am using pjax with Yii2 and I have faced a problem with pjax. All scripts are working correctly and fine only the first time and after sending a pjax request and updating the table content, scripts and pjax not working. If I remove the line $.pjax.reload({container:'#products-table'});
all scripts are working. And also I found this solution ( Yii2 Pjax and ActiveForm beforeSubmit not working after reload? ): " $(document).on('ready pjax:success', function(){ // to do });
" and with it working fine BUT after adding more jquery code it stopped working again. Please if someone has the same issue please share with solution. Thanks!
$(document).on('ready pjax:success', function(){
$(".product-edit-submit").on('click', function(){
$.ajax({
type : "POST",
url : editUrl,
data: {
id: this.id,
productName: productName,
productCost: productCost,
_csrf: csfr
},
success : function(response) {
$.pjax.reload({container:'#products-table'});
},
error : function(response){
console.log(response);
}
});
return false;
});
});
<?php Pjax::begin(['id' => 'products-table']); ?>
<table class="table table-hover table-striped">
.......
</table>
<?php Pjax::end(); ?>
if your code stops after adding extra libraries try registering it in view to make sure it will execute after all libraries included:
<?php
$js = <<< 'JAVASCRIPT'
$(document).on('ready pjax:success', function(){
$(".product-edit-submit").on('click', function(){
$.ajax({
type : "POST",
url : editUrl,
data: {
id: this.id,
productName: productName,
productCost: productCost,
_csrf: csfr
},
success : function(response) {
$.pjax.reload({container:'#products-table'});
},
error : function(response){
console.log(response);
}
});
return false;
});
});
JAVASCRIPT;
$this->registerJs($js,\yii\web\View::POS_READY);
I found the reason why the second time scripts are not triggering. I putted the script outside of $(document).on('ready pjax:success', function(){ //code });
. After putting it inside of pjax:success
, all the scripts are working again. Thanks!
Just Change this line $(".product-edit-submit").on('click', function(){
to :
$(document).on('click', '.product-edit-submit', function () {
Then It will work