How to update Data from a Select with Ajax?

Asked

Viewed 487 times

1

I have the following question, I have a modal, where I enter a city, so I need my select to be 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>

1 answer

0


Add it to <select> desired. Simply insert an element <option>.

CODE

This would be a POST request to do the insertion of the municipality. I want that only consider the callback function. Assuming the return of the request is a JSON of the form {"id_municipio": "...", "nome_municipio": "..."} 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 someway would be where the request would be sent (a PHP file for example), data would be the data passed via request, collected by the modal.

Browser other questions tagged

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