L
L
Lev K2016-04-18 15:21:42
JavaScript
Lev K, 2016-04-18 15:21:42

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);

What url should be registered to send data to the controller? I created an action in it to process the dynamics, I did not create the view file itself. And how then to return result?
_
Made the following changes:
script
<?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);


controller
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();
    }

Gives an error Internal Server Error, ajax request is not executed, "error" pops up

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
VZVZ, 2016-04-18
@VZVZ

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

P
polar-bear, 2016-04-18
@polar-bear

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 question

Ask a Question

731 491 924 answers to any question