carga.html
Código HTML:
Ver original<!DOCTYPE html>
LoadData = function(url) {
this.search = this.search.bind(this);
this.load = this.load.bind(this);
this.url = url;
this.form = null;
}
LoadData.prototype = {
"search" : function(form) {
this.form = form;
this.load(new FormData(this.form), function(status, response) {
if(status === 200) {
response = JSON.parse(response);
for(var name in response)
this.form.elements[name].value = response[name];
}
});
},
"load" : function(params, callback) {
var request = new XMLHttpRequest();
request.open("POST", this.url);
request.onreadystatechange = function(callback) {
if(this.readyState == 4)
callback(this.status, this.responseText);
}.bind(request, callback.bind(this));
request.send(params);
}
};
<h1>Carga de formulario de busqueda via json
</h1> El codigo:
<input type="text" name="codigo" value="5"> Nombres:
<input type="text" name="nombres"> Apellidos:
<input type="text" name="apellidos"> Documento:
<input type="text" name="documento_nro"> <input type="reset" value="VACIAR">
document.getElementById("load").addEventListener("click", function() {
(new LoadData("search.php")).search(document.getElementById("datos-origen"));
});
search.php
Código PHP:
Ver original<?php
/* Config */
$db = ["localhost", "root", "", "db_name"];
$table = "contactos";
$fields = [
"codigo" => "=",
"nombres" => "%LIKE%",
"apellidos" => "%LIKE%",
"documento_nro" => null
];
$result = false;
if($mysqli = new MySQLi($db[0], $db[1], $db[2], $db[3])) {
$where = "";
foreach($filter as $key => $type) {
$where .= ($where ? " AND " : "");
switch($type) {
case "=" :
$where .= "$key = ?";
break;
case "%LIKE%" :
$where .= "$key LIKE ?";
$_POST[$key] = "%" . $_POST[$key] . "%";
break;
}
}
if($where)
$where = "WHERE $where";
if($stmt = $mysqli->prepare("SELECT " . implode(", ", array_keys($fields)). " FROM $table $where LIMIT 1")) {
foreach($filter as $key => $type)
$stmt->bind_param("s", $_POST[$key]);
$stmt->execute();
if($result = $stmt->get_result()) {
$result = $result->fetch_array(MYSQLI_ASSOC);
foreach($result as &$value)
}
$stmt->close();
}
$mysqli->close();
}
if(!$result)