How to update a Select Data with Ajax?

1

I have the following doubt, I have a modal, where I enter a city, so I need to have my select reloaded showing this newly added option, without the page being updated:
Select:

<select id="idMunicipio" name="idMunicipio" class="form-control">
  <?php foreach ($municipios as $municipio) : ?>
  <option value="<?=$municipio->idMunicipio?>"><?=$municipio->municipio?></option>
  <?php endforeach ?>
</select>
    
asked by anonymous 18.12.2017 / 01:06

1 answer

0

Add it to the% desired%. Just enter a <select> element.

CODE

This would be a POST request to do the insertion of the municipality. I want to watch only the callback function . Assuming the return of the request is a JSON of the form <option> then we can make the following code:

$.post('algum_caminho', dadosMunicipio, function(data){
  $('select[name=idMunicipio]').append('<option value="'+data.id_municipio+'">'+data.nome_municipio+'</option>');
});

Where some_path would be where the request would be sent (a PHP file for example), Municipal data would be the data passed via request, collected by modal.     

18.12.2017 / 05:08