What method do I use to mark a BD search result checkbox in ajax?

Asked

Viewed 42 times

1

I need to mark checkboxs for a page of editing forms, the values are saved in a table where checkboxs that were marked in the register were stored, but I do not know how to pull these results and leave marked the same fields editing page, Treating each client would generate a lot of inconvenience because the searches are done via ajax which makes it a little difficult because my knowledge is greater in php. Results are generated in php through json_encode

Structure of the BD

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

      }
    }
});

Structure of PHP

<?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'];);
    }
}

1 answer

2


To send the data back to the customer you can use echo json_encode($imprime);. So send 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);

who will send [{"a":true},{"b":true},{"c":false}] for 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’t implement add more data to the question to help more.

Browser other questions tagged

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