Which method to use to checkbox a search result to the DB made in ajax?

1

I need to checkboxes for a forms editing page, the values are saved in a table where the checkboxes that have been marked in the register have been stored, however I do not know how to pull those results and leave the same fields edit page checked, treating each client would generate a lot of inconvenience because the searches are done via ajax which makes it a bit difficult because my knowledge is greater in php. The results are generated in the php through json_encode

DB Structure

CREATE TABLE produtos (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
id_cliente INT(6) NOT NULL,
id_produto INT(6) NOT NULL,
reg_date TIMESTAMP
)

Javascript Structure

$.ajax({
    type:'post',        
    dataType: 'json',   
    url: produtos.php',
    data:{id:idcliente},
    success: function(result){

    //como colocar o resultado da busca aqui

      }
    }
});

PHP framework

<?php

require('conn/conn.php');

$cliente = $_POST['id'];

$qryprodutos = mysqli_query($con, "SELECT * FROM produtos where id_cliente=$cliente");
$num = $qryprodutos->num_rows;

if($num > 0){
    while($resultado = mysqli_fetch_assoc($qryprodutos)){
        $imprime[] = array("produto"=>$resultado['id_produto'];);
    }
}
    
asked by anonymous 20.12.2016 / 06:20

1 answer

2

To send the data back to the client you can use echo json_encode($imprime); . So you're sending a JSON back.

An example in PHP would be:

$arr[] = array('a' => true);
$arr[] = array('b' => true);
$arr[] = array('c' => false);
echo json_encode($arr);

which will send [{"a":true},{"b":true},{"c":false}] to JavaScript.

Then in JavaScript / jQuery you can do:

$.ajax({
    type: 'post',
    dataType: 'json',
    url: produtos.php,
    data: {
        id: idcliente
    },
    success: function(result) {
        result.forEach(function(obj){
            var id = Object.keys(obj)[0];
            var el = document.getElementById(id);
            el.checked = obj[id];
        });
    }
});

It was an example, if you can not put together more data to the question to help us more.

    
20.12.2016 / 07:04