Completing form with AJAX and MySql

2

I need to complete a form, according to user demand, with information from the Database (MySql).

Example:
I have the fields "Institution", "Course" and "Period". For the user, firstly, only the "Institution" option will appear, once he has selected the desired institution, the course options will appear in the field below and he will have the "Institution" and "Course" fields visible as soon as he selects the course will appear in the field below the period options and it will have the fields "Institution", "Course" and "Period" visible.

Attempt:
I used the following script to make Ajax requests:

    function consulta(){
        var xmlreq = CriaRequest();
        var result  = document.getElementById("instituicao");;
        xmlreq.open("GET", 'curso.php', true);
        xmlreq.onreadystatechange = function(){
        (readyState=4)
        if (xmlreq.readyState == 4){
            if (xmlreq.status == 200){
                result.innerHTML = xmlreq.responseText;
                }else{
                    result.innerHTML = "Erro: " + xmlreq.statusText;
                }
            }
        };
        xmlreq.send(null);
}

But I did not get the desired result because I would have to make a script like this for every demand.

Question:
Is there any way I can use ONLY ONE SCRIPT for all three actions?

    
asked by anonymous 15.06.2015 / 19:35

2 answers

2

I've added some parameters to your function, so the part of code that will be repeated will be smaller.

function consulta(url, resultId){
    var xmlreq = CriaRequest();
    var result = document.getElementById(resultId);
    xmlreq.open("GET", url, true);
    xmlreq.onreadystatechange = function(){
        (readyState=4)
        if (xmlreq.readyState == 4){
            if (xmlreq.status == 200){
                result.innerHTML = xmlreq.responseText;
            } else {
                result.innerHTML = "Erro: " + xmlreq.statusText;
            }
        }
    };
    xmlreq.send(null);
}

Call the function like this: consulta('curso.php', 'instituicao') and consulta('periodo.php', 'curso')

    
15.06.2015 / 19:47
2

There, I usually do this:

function ajax(url, params, complete) {
   var xhr = CriaRequest(); // Não sei oq isso faz, estou seguindo seu padrão
   xhr.open("GET", url, true);
   xhr.onreadystatechange = function(){
       if (xmlreq.status == 200 && xmlreq.readyState == 4){
            complete(xhr.responseText);
       }
    }
  xhr.send(JSON.stringify(params));
}

What the ajax method receives:

  • URL: This is the url that should receive the request
  • Params: An object with all the attributes that should be sent to the server
  • Complete: Callback responsible for doing something with return.

So you can send whatever you want to the server and treat the return in the way that suits you best:

Let's suppose you have a select like this:

<select id='uf' onchange='carregarCidades(this.value)'>
   <option value='1'>ES</option>
   <option value='2'>RJ</option>
   <option value='3'>SP</option>
   <option value='4'>MG</option>
</select>

The carregarCidades function would be written like this:

function carregarCidades(uf){
    var parametros = new Object(); // ou 'Object.create', tanto faz
    parametros.uf = uf; // Aqui eu crio um atributo uf que será enviado para o servidor
    ajax('url-do-seu-serviço', parametros, function(results){
        var result = document.getElementById("resultId");
        result.innerHTML = results;
    });
}

Note that I created an anonymous function and passed as callback. Inso is heavily used in JS. An alternative and more readable way would be to do this:

function printCidades(cidades){
    var result = document.getElementById("selectCidades");
    result.innerHTML = results;
}

function carregarCidades(uf){
    var parametros = new Object(); // ou 'Object.create', tanto faz
    parametros.uf = uf; // Aqui eu crio um atributo uf que será enviado para o servidor
    ajax('url-do-seu-serviço', parametros, printCidades);
}

What's important is to define what kind of data your server is waiting for. The way I did it it gets a JSON object with an attribute, in this case, uf .

Another important thing is return. It would be cool if it was JSON too.

    
15.06.2015 / 19:58