I
I
Ivan Petrov2017-06-02 19:09:08
JavaScript
Ivan Petrov, 2017-06-02 19:09:08

How to properly implement live search in yii1?

Hello. I did a live search, but in yii1 it breaks everything that is possible. What is the best way to structure this whole thing?

Now I just put the JS and the handler in a separate folder:

JS code:

$(function() {

            //Живой поиск
            $('.who').bind("change keyup input click", function() {
                if (this.value.length >= 2) {
                    $.ajax({
                        type: 'post',
                        url: "/testing/search.php", //Путь к обработчику
                        data: { 'referal': this.value },

                        response: 'text',
                        success: function(data) {
                            $(".search_result").html(data).fadeIn(); //Выводим полученые данные в списке
                        }
                    })
                }
            })

            $(".search_result").hover(function() {
                $(".who").blur(); //Убираем фокус с input
            })

            //При выборе результата поиска, прячем список и заносим выбранный результат в input
            $(".search_result").on("click", "li", function() {
                s_user = $(this).text();
                $(".who").val(s_user).attr('enabled', 'enabled'); //деактивируем input, если нужно
                $(".search_result").fadeOut();
            })

        })


Handler code:
if(!empty($_POST["referal"])){ //Принимаем данные

        $referal = trim(strip_tags(stripcslashes(htmlspecialchars($_POST["referal"]))));

        $db_referal = $mysqli -> query("SELECT * from city WHERE name LIKE '%$referal%'");

        while ($row = $db_referal -> fetch_array()) {
            echo '<ul class="results">';
            echo "\n<li>".$row["name"]."</li></ul>"; //$row["name"] - имя поля таблицы
            
        }


and in main:
<div class="search_result"></div>
$(function (){ 
    $('.searchCity').click(function(){
       var text = $('.who').val(); 
       $('.cityChange').text(text);
    });
});


As it will be correct, according to MVC it ​​is organized. If the handler is thrown into the model, is it possible to separately access the method somehow? Or are there other solutions? Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2017-06-02
@webinar

Why a model? The request must go to the controller, there, refer to the model and its methods, to receive data and pass the model to the view.
I don’t remember yii1 anymore, in yii2 I would stuff all the html and js into the widget.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question