N
N
nevesomostjke2022-01-24 15:30:28
AJAX
nevesomostjke, 2022-01-24 15:30:28

Why don't JS scripts work in AJAX response?

Hello!
Can someone tell me, I have such a problem.
I'm making a category selection page. I want it to be on Ajax.
The idea is that there is a select with a choice, where there is a list of all brands of cars. The user selects a brand and he has a new select with a list of models on the same page. Those. sends a POST to the controller and the controller returns a view with a different list.
There are a lot of models in the categories and it will not work to load all the categories onto the page at once.

Everything seems to be fine, the answer comes, but my whole problem is that I use the select 2 JS plugin, and when a view with a new dropdown list is returned to the user, JS scripts are disabled (i.e. the new dropdown list does not work). I tried 100500 ways, nothing comes out for me.

I tried 100500 ways in a day, https://qna.habr.com/q/63544 - it did not help me.
Can anyone tell me which way to look, where there is a specific working sample, such that JS scripts work in the returned view? Maybe it would be correct to implement this in JSON? If on JSON, I'm very weak in it, give me a sample.
Laravel 8.

/// upd
Solved by initializing select 2 in ajax response

function sendform(form, way, status)  { 
    var msg   = jQuery(form).serialize(); // ID формы
      
        jQuery.ajax({    
        method: 'POST', // Метод отправки
        url: way, // Адрес обработчика
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        beforeSend: function(){
        jQuery(status).html('Отправляю...'); // Промежуточный статус
        },
        data: msg,
        cache: false,  
        success: function(html){  
          $(function(){
                $('select').select2();
              });
        jQuery(status).html(html);  }  });  // Вывод ответа

  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur Maslov, 2022-01-24
@tmaslov22

The server should give a response in json format and then pass this data to select2 through js code.
See the example in the doc

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question