B
B
bk_maestro2018-11-13 17:32:08
Yii
bk_maestro, 2018-11-13 17:32:08

Native Ajax request in yii2?

You need to sort by date.
I do through a self-written calendar. Its essence is very simple - it gets the value of the field where the user clicked and, by means of an ajax request, pass it to the controller, which will render a table with data.
The problem is that you need to specify the correct path to the controller.

$('.month').click(function() {
    var date = $(this).text();

    $.ajax({
        url: '/user/admin/apartment?action=new',
        date: date,
        method: 'post',
        dataType: 'json',
        success: function () {
            alert('success');
        },
        error: function (response) {
            console.log(response);
        }
    })
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2018-11-13
@bk_maestro

Good evening.
There are at least two options here.
The easiest is to form a variable with an address and pass it to js, ​​while you need to correctly connect js

$url = Utl::toRoute(// путь к Вашему контролеру/действию.);
$this->registerJs(
"
$('.month').click(function() {
    var date = $(this).text();

    $.ajax({
        url: '".$url."',
        date: date,
        method: 'post',
        dataType: 'json',
        success: function () {
            alert('success');
        },
        error: function (response) {
            console.log(response);
        }
    })
});
", yii\web\View::POS_END)

This is if js is in the same file.
If you have js in a separate file, then I would add an additional parameter, for example, to the link in which the url would be stored. When clicking on the link, I would read this parameter and form the url for the ajax request from it.
Example:
php
js
$('a').on('click', function(){
  var url = $(this).attr('data-ajaxurl')
 $.ajax({
    url: url
 })
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question