Rescue data from checkbox stored in the bank

Asked

Viewed 560 times

2

I am recording data from 6 checkboxes in the database. I am treating each one separately, as below:

              <tr>
              <td>Tabela Nutricional:</td>
              <td><input type="checkbox" name="export_tabela[1]" id="export_tabela[1]" value="PORTUGUES"> Português
                  <input type="checkbox" name="export_tabela[2]" id="export_tabela[2]" value="INGLES"> Inglês
                  <input type="checkbox" name="export_tabela[3]" id="export_tabela[3]" value="ESPANHOL"> Espanhol
                  <input type="checkbox" name="export_tabela[4]" id="export_tabela[4]" value="FRANCES"> Francês
                  <input type="checkbox" name="export_tabela[5]" id="export_tabela[5]" value="ARABE"> Árabe
                  <input type="checkbox" name="export_tabela[6]" id="export_tabela[6]" value="COREANO"> Coreano</td>
              </tr>

I can record all that were marked in the registration page and in the table is correctly:

inserir a descrição da imagem aqui

My problem is that when it comes to rescuing the data using Ajax, it does not mark any value in the checkbox of the editing page, whose HTML is the same as the registration page. The Ajax I use, shown below, saves correctly in all other fields, takes the id and saves the value:

       // Verifica se foi concluído com sucesso e a conexão fechada (readyState=4)
        if (xmlreq.readyState == 4) {
            // Verifica se o arquivo foi encontrado com sucesso
            if (xmlreq.status == 200) {
                //Se o retorno foi vazio do MySQL
                if (xmlreq.responseText == "") {
                    document.getElementById("projeto").focus();
                    alert("Não existe o projeto informado!");
                    ids.forEach(function (id) {
                        document.getElementById(id).value = '';
                        document.getElementById("projeto").value = '';
                    });
                //Se encontrou dados
                } else {
                    //Aqui recebe os dados do processa.php, abre e aplica nos campos desejados
                    var dados = JSON.parse(xmlreq.responseText);
                    // função para preencher os campos com os dados
                    ids.forEach(function (id) {
                        document.getElementById(id).value = dados[id];
                    });
                }
            } else {
                result.innerHTML = "Erro: " + xmlreq.statusText;
            }
        }

Any suggestions how I can bring the fields and mark them on the update page?

  • I think at the same time .value you want to use .checked which is the property that marks/unchecks. How does this database value come and then JSON parse? comes as string or Boolean? If it’s boolean just use: document.getElementById(id).checked = dados[id];

  • The data goes to ajax as array. Vc says edit ajax at the time of "load" of the values?

  • From what I read in the question, the send-to-BD part works, but you’re having trouble marking/unchecking when you want to reassemble that information with BD data, right? in this case depends on how Ravas in the BD and how you return via ajax. If you save the status checked/not checked as string or as Boolean?

  • Exactly, the recording is ok, my problem is in return. Actually I did not save the state, saved the field value: <input type="checkbox" name="export_table[1]" id="export_table[1]" value="PORTUGUES">. How I record the state?

  • It depends on how you send it to the server. If you send a form to PHP only the ones that are marked are passed with the form. If you go through ajax you have to check the input.checked and delete the ones that aren’t marked, if it’s the first case then you can just do .checked = true; for those in the database, that is in the JSON that came from the server.

  • Thanks for the help @Sergio, I used your suggestion from . checked, I divided the way to rescue the data and it worked. Thanks.

  • You’re welcome. I’ve put together a more complete answer and a suggestion for optimisation.

Show 2 more comments

2 answers

2

To mark a checkbox you need to give a boolean value to the property checked of the element.

How are you wearing one <form> to send the original data to PHP then only the checked checkbox will be sent, which means that when restoring this state you can mark as .checked = true; all those who are part of that JSON.

You can then do so in your loop:

var dados = JSON.parse(xmlreq.responseText);
// função para preencher os campos com os dados
ids.forEach(function (id) {
    document.getElementById(id).checked = true;
    document.getElementById(id).value = dados[id];
});

But you can optimize this code if you already have an object with these Ids, so avoid using getElementById or querySelector excessively as in the example above. It would be something like:

// quando a página carrega fazes cache desses elementos
var checkboxes = {};
["export_dizeres[1]", "export_dizeres[2]", "export_dizeres[3]","export_dizeres[4]", "export_dizeres[5]", "export_dizeres[6]", "export_tabela[1]", "export_tabela[2]", "export_tabela[3]", "export_tabela[4]", "export_tabela[5]", "export_tabela[6]"].forEach(function(id){
    checkboxes[id] = document.getElementById(id);
});

// e depois dentro do ajax basta fazer:

var dados = JSON.parse(xmlreq.responseText);
// função para preencher os campos com os dados
ids.forEach(function (id) {
    checkboxes[id].checked = true;
    checkboxes[id].value = dados[id]; // caso queiras também setar o valor
});

0


Solved by editing the ajax: I declared the checkbox ids separately:

    var ids2 = ["export_dizeres[1]", "export_dizeres[2]", "export_dizeres[3]","export_dizeres[4]", "export_dizeres[5]", "export_dizeres[6]", "export_tabela[1]", "export_tabela[2]", "export_tabela[3]",
           "export_tabela[4]", "export_tabela[5]", "export_tabela[6]"];

Then, when it was time to load the data, I used @Sergio’s suggestion:

                    ids2.forEach(function (id2) {
                    document.getElementById(id2).checked = dados[id2];
                });

Thanks for the help.

Browser other questions tagged

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