Answer the question
In order to leave comments, you need to log in
How to send ajax request to controller?
Hello.
I'm trying to implement dynamics in yii2.
Selected the required form block in pjax.
Created a button and an event for it.
But the ajax request doesn't work.
<?php
$js = "$('#btn_add').on('click', function () {
$.ajax({
url: ,
type: 'POST',
data: $action='two',
success: function(response) {
$.pjax.reload({container: '#pjax-form1'});
}
});
return false;
})";
$this->registerJs($js);
<?php
$js = "$('#btn_add').on('click', function () {
$.ajax({
url: '/trip/add',
type: 'POST',
dataType: 'json',
data: { 'action' : 'two' },
success: function(response) {
$.pjax.reload({container: '#pjax-form1'});
},
error: function(){
alert('error')
}
});
return false;
})";
$this->registerJs($js);
public function actionAdd()
{
$count = $_POST['action'];
if ($count == 'two') $c = 2; else $c = 1;
$modelCouples = [new Couple()];
for ($i = 1; $i < $c; $i++) {
$modelCouples[] = new Couple();
}
$res = Yii::$app->getResponse();
$res->format = Response::FORMAT_JSON;
$res->data = $modelCouples;
$res->send();
}
Answer the question
In order to leave comments, you need to log in
I don't know what registerJs is.
In general, the URL should look like this:
localhost/index.php?r=site/add
Or like this:
localhost/site/add
Where the controller is called Site Controller. In short, everything is exactly the same as if without ajax
As for returning a value, I would return a JSON string, check it in the browser (address bar) and only then write client code
If the view in which you wrote the JS is in the context of the controller to the action of which you send the request, then you can:
or
In the action, it might be worth putting:
Yii::$app->response->format = Response::FORMAT_JSON
and then Yii will return the response in json format. A to the ajax config object:'dataType': 'json'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question