Ajax, Javascript and PHP form

Asked

Viewed 535 times

0

How can I make a form with a UF field and a selection field with label Cities that will be filled through AJAX and that when selecting the UF the JS function connects to the server and returns the cities of that UF, but without searching in the Database? I was directed to do with a switch-case structure or something similar that returns values from a key value, but I have no idea how it works. I just have an idea how to do using the database.

NOTE: I decided to do with the database, because I think it is more practical.

I already made the form:

<form name="formCadastro" action="buscaCidade.php" method="post">

    <label>Nome</label>
    <input type="text" name="name" placeholder="Digite seu nome" required>  

    <label>E-mail</label>
    <input type="email" name="email" placeholder="Digite seu email">    

    <label>UF</label>
    <select name="uf">
    </select>

    <label>Cidade</label>
    <select name="cidade">

        <!--INSERIR AQUI AS OPÇÕES DE CIDADE-->

    </select>

    <input type="submit" name="submit" value="Enviar">


</form>

And I also made the bank, which would be something like this:

DROP TABLE IF EXISTS `cidades`;
DROP TABLE IF EXISTS `estados`;


CREATE TABLE `cidades` (
  `estados_cod_estados` int(11) DEFAULT NULL,
  `cod_cidades` int(11) DEFAULT NULL,
  `nome` varchar(72) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cep` varchar(8) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


CREATE TABLE `estados` (
  `cod_estados` int(11) DEFAULT NULL,
  `sigla` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  `nome` varchar(72) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Now I’m finishing PHP.

  • What have you ever done?

  • I made HTML, BD and now I’m finishing PHP.

1 answer

0


Jamile would a use of an API with states and cities help you? I don’t know if it would solve but here’s what I was thinking, that way you would have the option of city and states without having to select in the bank and not even have those values stored in them

//jquery var do select dos estados
var $selectUf = $("#selectUf"); 

//jquery var do select das cidades
var $selectCidades = $("#selectCidade");

//será atribuido um valor nessa variável sempre que ele escolher um UF
var estadoSelecionado; 
var cidadeSelecionada;

//uma função que pega os estados da API e o parametro dela recebe uma função que lida com essa resposta
var getEstados = function(responseFunction){  
  $.ajax({
    method: "GET",
    url: "http://api.londrinaweb.com.br/PUC/Estados/BR/0/10000",
    contentType: "application/json; charset=utf-8",
    dataType: "jsonp",
    async:false,
    success: responseFunction
  });
}

//mesma ideia da função de cima porém nessa pegaremos a cidade de acordoo com a UF escolhida
var getCidades = function(estadoSelecionado,responseFunction){
  $.ajax({
    method: "GET",
    url: "http://api.londrinaweb.com.br/PUC/Cidades/"+estadoSelecionado+"/BR/0/10000",
    dataType: "jsonp",
    success: responseFunction
  });
}

//função que lida com a resposta da api e lista os estados no select
var populandoSelectUf = function(response) {
  $.each(response,function(i,item){
    $selectUf.append('<option value="'+item.UF+'"> '+item.UF+' </option>');
  })
}

//essa função só é chamada quando escolhe algum estado da UF
var populandoSelectCidades = function(response){
  //limpando o html do select
  $selectCidades.html("");
  $.each(response,function(i,item){
    $selectCidades.append('<option value="'+item+'">'+item+'</option>')
  });
}

getEstados(populandoSelectUf);

//sempre quando escolher uma UF coloca o valor selecionado na variavel estado selecionado
//e depois disso lista as cidades correspodente a UF Escolhida
$selectUf.change(function(){
  estadoSelecionado = $(this).val();
  alert("voce selecionou: "+estadoSelecionado);
  getCidades(estadoSelecionado,populandoSelectCidades);
});

$selectCidades.change(function(){
  cidadeSelecionada = $(this).val();
  alert("voce selecionou: "+cidadeSelecionada);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="formCadastro" action="buscaCidade.php" method="post">

  <label>Nome</label>
  <input type="text" name="name" placeholder="Digite seu nome" required>

  <label>E-mail</label>
  <input type="email" name="email" placeholder="Digite seu email">

  <label>UF</label>
  <select name="uf" id="selectUf">
  <option selected="true" disabled>UF</option>
  </select>

  <label>Cidade</label>
  <select name="cidade" id="selectCidade">

    <!--INSERIR AQUI AS OPÇÕES DE CIDADE-->

  </select>

  <input type="submit" name="submit" value="Enviar">


</form>

  • Reynnan, I would help, and I really appreciate your kindness in helping me. But I have specifics to follow, are they: A selection field with label City that will be filled through AJAX with at least 5 cities of each UF. When selecting the UF the JS function connects to the server and returns the cities of that UF. You do not need to search the database, you can use a switch-case structure or something similar that returns values from a key value. A button type button with value "Display". On onclick, display an Alert with the message showing the UF and the city.

  • @Jamilelima then you could do something like the response of a JSON as in the API, when selecting the UF, you would give a $.get to the desired url by sending the value of the UF chosen so in that url you checked which Uf chosen if $_GET['Uf'] == "SE" echo "Aracaju, Itabaiana..." and with the answer of this URL you would list the cities of the chosen UF, sorry if it got a little messy this comment but basically would work well like the API.

  • Thanks for your help, Reynnan! I’ll try it here!

Browser other questions tagged

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