The following scenario is presented to me, I have in my HTML
a <textarea>
in which the user will enter a query, as if it were the command line, example, I can enter:
SELECT * FROM users;
SELECT * FROM countries;
SELECT email, nickname, range FROM users WHERE userID = 1;
With a request AJAX
I send the query that I want, it returns me a JSON
that contains the records of the query.
For example, for the first query above, the generated JSON is as follows:
And for the second query is the following:
How can I navigate through these JSONs? Obtaining the headers and their registers, in order to generate a table HTML
with the data obtained.
This is what I have in my file JS
I get the records and create the tables, but without their corresponding headers.
$(document).ready(function() {
$('#realizarQuery').click(function(event) {
event.preventDefault();
var valorTextArea = $('#valorTextArea').val();
$.ajax({
url: 'realizarQuery.php',
type: 'POST',
dataType: 'JSON',
data: {valorTextArea},
})
.done(function(data) {
console.log("success");
console.log(data);
console.log(typeof data);
$.each(data, function(index, val) {
if (val == '¡Escribe tu query!') {
$('#texto').html('¡ESCRIBE TU QUERY!').css('font-size', '20px').css('color', '#D50000');
$("#registrosIntermedios").html('').hide();
}else if( val == '¡Verifique su sentencia SQL!'){
$('#texto').html('¡VERIFIQUE SU SENTENCIA SQL!').css('font-size', '20px').css('color', '#D50000');
$("#registrosIntermedios").html('').hide();
}else{
var tbl_body = "";
var odd_even = false;
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>";
odd_even = !odd_even;
})
$('#texto').html('LOS REGISTROS QUE CONTIENE SU CONSULTA SON LOS SIGUIENTES').css('font-size', '20px').css('color', '#2E7D32');
$("#registrosIntermedios").html(tbl_body).show();
}
});
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
}, 'json');
});
});
For any contribution, thank you.