Visualizzazione dei risultati da 1 a 5 su 5

Discussione: Select 2 ajax request

  1. #1

    Select 2 ajax request

    Salve a tutti , sto facendo una richiesta da un database dei comuni per popolare una select2 ,
    il codice del select2 (preso da un tutorial e adattato � :

    codice:
         // Initialize select2
         $("#id_id_comuni").select2({
            theme: "bootstrap-5",
            ajax: { 
              url: "<?= base_url('AjaxRequest/getComuniSelect')?>",
              type: "post",
              dataType: 'json',
              delay: 250,
              data: function (params) {
                 // CSRF Hash
                 var csrfName = $('.txt_csrfname').attr('name'); // CSRF Token name
                 var csrfHash = $('.txt_csrfname').val(); // CSRF hash
    
    
                 return {
                    searchTerm: params.term, // search term
                    [csrfName]: csrfHash // CSRF Token
                 };
              },
              processResults: function (response) {
    
    
                console.log(JSON.stringify(response.data));
     
                 // Update CSRF Token
                 $('.txt_csrfname').val(response.token); 
    
    
                $.each(response.data, function (i) {
                    $.each(response.data[i], function (key, val) {
                        $("#id_id_comuni").text("<option value='"+val.id+"'>"+val.cap+" "+val.localita+"</option>")
                    });            
                });
    
    
                return {
                    results: response.data
                };
    
    
    
    
              },
              cache: true
            }
         });
    )

    se guardo il console.log ho i dati sotto forma di json come mi aspetto ma non ho le option...

  2. #2
    Moderatore di CSS L'avatar di KillerWorm
    Registrato dal
    Apr 2004
    Messaggi
    5,695
    Ciao, penso che il problema sia nell'uso del metodo text() di jQuery:

    codice:
    $("#id_id_comuni").text("<option value='"+val.id+"'>"+val.cap+" "+val.localita+"</option>")
    Come è logico pensare, questo metodo inserisce del contenuto testuale dentro l'elemento in questione. Quello che viene passato a tale metodo è quindi inserito come testo anche se presenta dei tag html come nel tuo caso.
    Infatti le parentesi angolari (< e >) vengono normalmente convertite in entità html se devono essere trattate come testo. Suppongo quindi che tu non veda nulla dentro il <select> perché il contenuto testuale non viene mostrato se non dentro regolari elementi <option>.

    Il metodo che dovresti usare è invece html().

    Prova e fai sapere.
    Installa Forum HTML.it Toolset per una fruizione ottimale del Forum

  3. #3
    con questo :


    codice:
            // Initialize select2     $("#id_id_comuni").select2({
            theme: "bootstrap-5",
            ajax: {
              url: "<?= base_url('AjaxRequest/getComuniSelect')?>",
              type: "post",
              dataType: 'json',
              delay: 250,
              data: function (params) {
                 // CSRF Hash
                 var csrfName = $('.txt_csrfname').attr('name'); // CSRF Token name
                 var csrfHash = $('.txt_csrfname').val(); // CSRF hash
    
    
    
    
                 return {
                    searchTerm: params.term, // search term
                    [csrfName]: csrfHash // CSRF Token
                 };
              },
                 processResults:  function (data) {
                            return {
                                results: $.map(data, function (item) {
    
    
    
    
                                    console.log(item)
                                    return {
                                        text: item.cap+' '+item.localita,
                                        slug: item.slug,
                                        id: item.id
                                    }
                                })
                            };
                        },
              cache: true
            }
         });

    ho undefined undefined, il console.log(item) scrivendo roma è allegato
    Immagini allegate Immagini allegate

  4. #4
    con questo invece :

    codice:
         // Initialize select2
         $("#id_id_comuni").select2({
            theme: "bootstrap-5",
            ajax: { 
              url: "<?= base_url('AjaxRequest/getComuniSelect')?>",
              type: "post",
              dataType: 'json',
              delay: 250,
              data: function (params) {
                 // CSRF Hash
                 var csrfName = $('.txt_csrfname').attr('name'); // CSRF Token name
                 var csrfHash = $('.txt_csrfname').val(); // CSRF hash
    
    
                 return {
                    searchTerm: params.term, // search term
                    [csrfName]: csrfHash // CSRF Token
                 };
              },
              processResults: function (response) {
    
    
                 console.log(JSON.stringify(response.data));
     
                 // Update CSRF Token
                 $('.txt_csrfname').val(response.token); 
    
    
                $.each(response.data, function (i) {
                    $.each(response.data[i], function () {
                        //console.log(response.data[i]['id']+' '+response.data[i]['cap'] );
                        $("#id_id_comuni").html("<option value='"+response.data[i]['id']+"'>"+response.data[i]['cap']+" " +response.data[i]['localita']+"</option>")
                    });            
                });
    
    
                return {
                    results: response.data
                };
    
    
    
    
              },
              cache: true
            }
         });
    scrivo nel input di select 2 appare correttamente il risultato ma non vedo le option

  5. #5
    Ho risolto con questo codice :

    codice:
    
         // Initialize select2
    
    
        $("#id_id_comuni").select2({
            theme: "bootstrap-5",
            ajax: {
              url: "<?= base_url('AjaxRequest/getComuniSelect')?>",
              type: "post",
              dataType: 'json',
              delay: 250,
              data: function (params) {
                 // CSRF Hash
                 var csrfName = $('.txt_csrfname').attr('name'); // CSRF Token name
                 var csrfHash = $('.txt_csrfname').val(); // CSRF hash
    
    
    
    
    
    
    
    
                 return {
                    searchTerm: params.term, // search term
                    [csrfName]: csrfHash // CSRF Token
                 };
              },
              processResults: function (response) {
     
                 // Update CSRF Token
                 $('.txt_csrfname').val(response.token); 
    
    
                 return {
                    results: response.data
                 };
              },
              cache: true
            }
         });

    data lato server arriva così :

    codice:
    foreach($lista_comuni as $comune){
             $data[] = array(
                "id" => $comune->id,
                "text" => $comune->cap.' '.$comune->localita,
             );
          }
    Le option hanno bisogno di 2 valori id (che diventa il value della option) e text (che diventa il testo che si vede premendo la select)

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.