How to submit forms automatically without submitting and without refreshing the page

0

Hello,

I'm a relatively new programmer in php and I'm developing a website. It is a site where there is a list of companies. And I wanted to implement in it, search filters, the first of them being a select "Select your city":

<form method="post" action="lista.php" id="Cidade" name="Cidade">
   <label for="cCidade">Selecione sua Cidade</label>
   <select id="cCidade" name="tCidade">
      <option>Selecione a Cidade</option>
      <option value="Farroupilha">Farroupilha</option>
      <option value="Caxias do Sul"default>Caxias do Sul</option>
   </select>
</form>

I want when the user uses select , the results are sent to a iframe on the screen (the "list.php"), which is the listing of companies as I said earlier. But I want this submission, do not refresh the page and do not even need a button to be sent, that is, whenever the user uses another select option, the search changes completely.

    
asked by anonymous 01.09.2016 / 00:15

1 answer

1

Good evening Nicolas,

To achieve this you should have some knowledge on AJAX and JavaScript . I'll try to explain how this would work.

First, you should know when select has been updated. To identify this, you need to hear an event of the select tag that fires every time select changes from option . You can achieve this goal with the following snippet:

var select = document.getElementById("cCidade");
    select.addEventListener("change", function(e){
        //O código aqui dentro será executado toda vez que usuário trocar o select
    });

Next, you need to send a request to the server asynchronously every time the user changes the city. It would look something like this:

var select = document.getElementById("cCidade");
    var xhttp;
    select.addEventListener("change", function(e){
        xhttp =  = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                //aqui dentro você manipula os dados das empresas retornados pelo servidor
            }
        };
        xhttp.open("GET", "lista.php?cidade" + select.value, true);
        xhttp.send();
    });

Notice that you are passing a parameter named city and dynamically taking the value of select.value . You may notice this in the line: xhttp.open("GET", "lista.php?cidade" + select.value, true);

Ready. This way you are not using any buttons or updating the page to have your data returned according to a dynamic query sent by the page.

If you are in doubt what is being done in this code, I suggest you search the web for the following topics.

  • How to make an AJAX request for PHP backend
  • What is a callback function
  • What XMLHttpRequest
  • How to listen to events in% with%

I hope you have helped.

    
01.09.2016 / 02:40