nwemember nwemember - 2 months ago 15
jQuery Question

Ajax success function shows "1" on the top left corner of blank page instead of refreshing the div

I am developing a yii2 application. I select data from the Bootstrap modal popup and submit to a controller action where I have an insert query. After I submit the data from modal popupthe data is submitted it shows a white page with "1" on the top left corner of the page instead of only closing the popup and refreshing the div but as I checked in the database data is inserted.

My part of code:
Pop Up call

<a class="btn btn-danger" data-toggle="modal" data-target="#modalgroup">+Add</a>


Modal pop up code:

<?php
Modal::begin([

'id' => 'modalgroup',
'size' => '',
'header'=>'<h3>Select Groups</h3>']);
$mymodel = new \app\models\Contact();
echo $this->render('group', ['mymodel'=>$mymodel]);
Modal::end();
?>


popup form

<?php
$form = ActiveForm::begin(['id'=>'select_group']);?>


<div class="row" style="height: auto;">


<div class="col-sm-8">
<div class="form-group form-group-sm field-profile-name">
<?php

$wishmodel = new GroupTran();
$wish=Group::find()->all();
$options =ArrayHelper::map($wish,'group_id','group_name');
echo $form->field($model, 'group_id')->checkboxList($options)->label('Select Groups').'<br>';
?>
</div>
</div>
</div>

<div class="form-group">
<?= Html::submitButton('Select', ['class' => 'btn btn-primary']) ?>
</div>
<?php
ActiveForm::end();


?>


My Js:

$url= Yii::$app->request->baseUrl.'/contact/group';

$( "#select_group" ).on('beforeSubmit', function(e) {
e.preventDefault();
var form= $(this);
$.ajax({
type: 'post',
url: '{$url}',
data: form.serialize(),
success: function () {
$(form).trigger("reset");
$('#modalgroup').modal('hide');
$('#groupdiv').load(window.location.href + '#groupdiv');
//$("#groupdiv").load(location.href+" #groupdiv>*");

}
});
return false;
});


my controller action

public function actionGroup()
{
$model = new Groups();
$post= Yii::$app->request->post();
$connection = \Yii::$app->db;
foreach(($post['GroupTran']['group_id']) as $data){
$wishdata = Groups::find()->where(['group_id'=>$data])->all();
if(!$wishdata)
$connection->createCommand()->insert('tbl_groups',['group_id'=>$data])->execute();
}

return true;
}


Please Help

Answer

Your on event for form i.e. beforeSubmit is invalid. Try replacing it with submit.

Because of this your form is submitting.

Replace $( "#select_group" ).on('beforeSubmit', function(e) {

To $( "#select_group" ).on('submit', function(e) {