Selecting and displaying data with Ajax

3

I have the following ajax :

var id = $('#idCliente').val();
$.ajax( 
{ 
    url:"/Administrar/chamadas/ajax/endereco/" + id, 
    dataType : 'json', 
    success:function(result) { 
        $('[name^="cham_endereco[]"]').val(result.endereco); 
        $('[name^="cham_numero[]"]').val(result.numero); 
        $('[name^="cham_cidade"]').val(result.cidade); 
        $('[name^="cham_bairro"]').val(result.bairro); 
    } 
});

In this case I retrieve the client address data, to automatically populate the fields, the return is as follows:

  

{"address": "R   MANDAGUARI "," Neighborhood ":" 25 "," City ":" 1 "," Status ": 16," CEP ": 83324410," Number ":" 1316 "

Until the return, all right. However, in the system I use a select to first select the city and then yes the neighborhood ... In this case, select the city automatically, however, the neighborhood is not selected (because it is not loaded by an ajax).

How can I call the neighborhood in ajax, so that it automatically loads on the screen and select the neighborhood that is being requested?

    
asked by anonymous 22.01.2016 / 13:22

2 answers

3

You can call ajax when you change the city field, if you already have the filled city field, you can call ajax when you finish loading the page.

To call when change does this way ...

$(function() {
  $('cidade').change(function(e) {
    //chama o ajax aqui
  }); 
});

If the field is already filled you can do so ...

$(function() {
  if ($('cidade').val() > 0) {
    //chama o ajax aqui
    //popule o campo estado
  } 
});

To populate the select field with the options get the return result of ajax and do so ...

$('bairro').append('<option value="0">Nome do Bairro</option>');

In your case it would look like this

<select id='cliente'>
  <option>Selecione o cliente</option>
  <option>Cliente 1</option>
  <option>Cliente 2</option>
</select>

<select  id='cidade'>
</select>

<select  id='bairro'>
</select>

And your script like this ...

$(function(){
  $('#cliente').change(function(e) {
      $('#cidade').append('<option value="1">Cidade 1</option>');
      $('#cidade').append('<option value="2">Cidade 2</option>');
      $('#cidade').val(2);
      $('#cidade').change();
    }); 
  $('#cidade').change(function(e) {
    //chama o ajax que busca os bairros aqui
    $('#bairro').append('<option value="1">Bairro 1</option>');
    $('#bairro').append('<option value="2">Bairro 2</option>');
    $('#bairro').val(2);
  }); 
});

See the example working here

    
22.01.2016 / 13:46
0

Shoot the 'change' event in the city selection box after selecting its value:

$('cidade').trigger('change');

Then after searching the neighborhoods select what comes from your Ajax.

    
29.01.2016 / 13:06