Problem with filter via JSON

1

Good evening,

I'm here with a filter problem via json for districts and counties to explain.

The user chooses a district and it filters and lists in another selectbox the counties that are associated with that district and the system is working the only problem and that in the counties several options appear as NULL.

Script

<script type="text/javascript">
$(function(){
    $('.carregando').hide();
    $('#distritos').change(function(){
        if( $(this).val() ) {
            $('#cod_cidades').hide();
            $('.carregando').show();
            $.getJSON('ajax/processa_concelhos.php?search=',{distritos: $(this).val(), ajax: 'true'}, function(j){
                var options = '<option value=""></option>'; 
                for (var i = 0; i < j.length; i++) {
                    options += '<option value="'+j[i].id_concelho+'">' +j[i].titulo+'</option>';
                }   
                $('#concelhos').html(options).show();
                $('.carregando').hide();
            });
        } else {
            $('#concelhos').html('<option value="">– Escolha um Concelho –</option>');
        }
    });
});

Select districts

<select name="distritos" id="distritos">
<option value="0">-- Escolha um Distrito --</option>
<?php
$sql = "select * from distritos order by titulo";
$res = mysql_query($sql);
while ($row=mysql_fetch_assoc($res)){
    echo '<option value="'.$row['id'].'">'.utf8_encode($row['titulo']).'</option>';
}
?>
</select>

Select counties

<select name="concelhos" id="concelhos">
 <option value="">-- Escolha um estado --</option>
</select>

Process_concelhos.php

<?php
require_once("../gtm/bd/funcoes.php");
ligarBd();  

$distritos =  $_REQUEST['distritos'] ;

$concelhos = array();

$sql = "select * from concelhos where id_mae='".$distritos."' order by titulo";
$res = mysql_query($sql);
while ($row=mysql_fetch_assoc($res)){
$concelhos[] = array(
    'id_concelho'   => $row['id'],
    'titulo'        => $row['titulo'],
);
}
echo( json_encode( $concelhos ) );
?>
    
asked by anonymous 18.02.2015 / 02:02

1 answer

3

The problem that was returning NULL values was due to the accentuation of some counties, so the solution went through using utf8_encode when returning values for it to read the accents.

Corrected solution code

<?php
require_once("../gtm/bd/funcoes.php");
ligarBd();  

$distritos =  $_REQUEST['distritos'] ;

$concelhos = array();

$sql = "select * from concelhos where id_mae='".$distritos."' order by titulo";
$res = mysql_query($sql);
while ($row=mysql_fetch_assoc($res)){
$concelhos[] = array(
'id_concelho'   => $row['id'],
'titulo'        => utf8_encode($row['titulo']), //linha corrigida
);
}
echo( json_encode( $concelhos ) );
?>
    
18.02.2015 / 02:26