Completing form with AJAX and Mysql

Asked

Viewed 316 times

2

I need to complete a form, according to the user’s demand, with Database information (Mysql).

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

Trying:
I used the following script to make the 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);
}

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

Question:
Is there any way I can use JUST ONE SCRIPT for the three actions?

2 answers

2

I added some parameters to your function, so the code part 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 that way: consulta('curso.php', 'instituicao') and consulta('periodo.php', 'curso')

2

There is, usually I do so:

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 attributes that should be sent to the server
  • Complete: Callback responsible for doing something with the return.

So you can send whatever you want to the server and treat the return the way it is most convenient:

Let’s assume 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 function carregarCidades 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 widely used in JS. An alternative and more readable way would be to do so:

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 is important is to define what kind of data your server is waiting for. The way I did it receives a JSON object with an attribute, in the case, uf.

Another important thing is the return. It would be nice if it were JSON as well.

  • I don’t quite understand your example, I’m sorry but I’m still beginner. Could you please give me some practical example.

  • 1

    See if Edit helps.

  • @Edgarmunizberlinck and after user select how this selected data can be sent to mysql. My case is as http://answall.com/questions/181981/form-din%C3%A2mico-e-send-to-mysql-via-jquery-e-ajax? noredirect=1#comment376494_181981

Browser other questions tagged

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