Load jQuery Multiselect options via Ajax

Asked

Viewed 814 times

0

Talk, you guys, baby?

I’m having a hard time. I have a modal, and wanted when making a select change, to press via ajax, to feed a jQuery multiselect. In a console.log I can see the output of options, but I cannot insert them into the Multiselect block.

Does this happen because of the DOM you’ve already loaded and I can’t fill it out anymore? I can’t get around it. My code looks like this:

In modal:

<div class="modal-body">
<div class="container">
    <div class="row">
        <div class="col-md-8">
            <div class="form-group">
                <label for="modulo" class="control-label">Nome do Curso</label>
                <input type="text" class="form-control" id="modulo" name="modulo" required/>
            </div>
        </div>
        <div class="col-md-2">
            <div class="form-group">
                <label for="tipo_modulo" class="control-label">Tipo do Módulo</label>
                <select class="form-control" id="tipo_modulo" name="tipo_modulo" required>
                    <option disabled selected value="">Selecione um Tipo</option>
                    <option value="basico">Básico</option>
                    <option value="especifico">Específico</option>
                </select>
            </div>
        </div>
        <div class="col-md-2">
            <div class="form-group">
                <label for="carga_horaria" class="control-label">Carga Horária</label>
                <input type="number" class="form-control" id="carga_horaria" name="carga_horaria" required/>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="form-group">
                <label for="nome_curso" class="control-label">Descrição do Módulo</label>
                <textarea class="form-control" id="descricao_curso" name="descricao_curso" required></textarea>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
        <div class="form-group">
            <label for="id_disciplina" class="control-label">Disciplinas Disponíveis</label>    
            <select name="id_disciplina" class="multi-select" multiple="" id="my_multi_select3">
                <div class="disciplinas"></div>
        </select>
    </div>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Fechar</button>
    <button type="submit" class="btn btn-info waves-effect waves-light">Cadastrar Módulo</button>
</div>

In my JS who does the ajax:

$("#tipo_modulo").change(function(){
    let tipo = $(this).children("option:selected").val();
    $.ajax({
        url: '../../assets/ajax/disciplinas.php',
        method: 'POST',
        data: {modo: tipo},
        dataType: 'html',
        success: function (result) {
            $(".disciplinas").html(result);

        }
    });
});

And in my file disciplines.php I already do a database search with my class already printing the options:

<?php
require('../../_app/Config.inc.php');
$post = filter_input_array(INPUT_POST, FILTER_DEFAULT);

if($post['tipo'] == 'basico'){
    $ReadDiscipline = new Read();
    $ReadDiscipline->ExeRead("disciplinas", "WHERE ativo = 1");
    foreach ($ReadDiscipline->getResult() as $disc):
        echo "<option value='{$disc['id']}'>{$disc['nome_disciplina']}</option>";
    endforeach;
}

What I want to fill in is this Multiselect field: https://imgur.com/MjU2PwO

If anyone can give me a light I’ll be very grateful kkkk =P Hug to all.

  • Is this Rafael blz? <div class="disciplinas"></div> within the select? Why you try to include the options within the select direct I think this way will work

  • Blz Thiago and you? I tried to use that <div> to create only the <options> in place. I tried as mentioned yet it does not feed the box. I tried also in my php already bring all html from the <select> still doesn’t work. It’s like the multiselect box only loads on the first page load.

2 answers

1


I found that jQuery’s own multiselect already has the functions to add the options inside select.

What I needed to do is to take the documentation of the layout of the array I need to pass as a parameter. In my PHP file, I transformed the result into an array, and then I echo it with json_encode, so I get the array ready to use when AJAX returns. It’s like this now

Select from simple HTML:

<select name="id_disciplina" class="multi-select" multiple="" id="my_multi_select3"></select>

In my JS I just switched the html dataType to JSON, and added the functions addOption and refresh of multiselect thus adding the option and clearing the fields every time I make a change, so it does not duplicate. I also put the refresh in the error because if not click for some reason do not leave the list with false information.

$("#tipo_modulo").change(function(){
    let tipo = $(this).children("option:selected").val();
    $.ajax({
        url: '../../assets/ajax/disciplinas.php',
        method: 'POST',
        data: {tipo: tipo},
        dataType: 'JSON',
        success: function (result) {                
            $('#my_multi_select3').multiSelect('refresh');
            if(tipo == 'basico'){
                $('#my_multi_select3').multiSelect('addOption', result);
            } else if(tipo == 'especifico') {
                $('#my_multi_select3').multiSelect('addOption', result);
            }
        },
        error: function(){
            $('#my_multi_select3').multiSelect('refresh');
        }
    });
}); 

And my PHP now looks like this:

$arr = [];
if($post['tipo'] == 'basico'){
    $ReadDiscipline = new Read();
    $ReadDiscipline->ExeRead("disciplinas", "WHERE tipo_modulo = 'basico' AND ativo = 1");
    $k = 0;
    foreach ($ReadDiscipline->getResult() as $disc):    
        $arr[$k] = [
            "value" => $disc['id'],
            "text" => $disc['nome_disciplina'],
            "index" => $k                
        ];
        $k++;
    endforeach;
    echo json_encode($arr);
}

In PHP I needed to add that $k as a key, because the index is what differentiates each of the options in jQuery, if I don’t define this, they all become as one and I can’t move from one frame to another. Follow the images working: DOM Carregado antes de fazer o change Change feito, carregou as opções Funcionando perfeitamnte de um quadro para o outro

I got the commands on that link: http://loudev.com/

Well that was it guys, I left the complete answer, if someone goes through the same doubt that’s how I solved =P

0

You are not able to include the options within select because when rendering the DOM to <div class="disciplinas"></div> is removed and Jquery is trying to include an html in a place that does not exist.

One solution to your problem would be to remove this div and change in Jquery:

$("#my_multi_select3").html(result);

That should solve!

  • Unfortunately it didn’t. It seems that since multiselect is already loaded in DOM, I can’t recreate it or add to options

Browser other questions tagged

You are not signed in. Login or sign up in order to post.