How to make a data query in HTML using javascritp or .json [closed]

1

Greetings I am working on an Html project with bootstrap in it I have to make some data queries by means of an ID. but as I have few data, I do not want to do a database and do some research, but I only find filtering tables, but the issue is that I do not want the data to be displayed until the search is done, so filtering tables does not suit me.

I can manage the data in .json files or javascritp bolt I do not know how to start. They can give me a hand or some advice how to start.

The following example shows the data but I do not want it to be visually until the filter is applied and I do not want it to filter until the button is pressed.

angular.module('busquedaAvanzada', [])
        .controller('busquedaController', ['$scope', function($scope){
            $scope.lista = [
                {nombre: 'Pepe', apellido: 'Trueno'},
                {nombre: 'Kava', apellido: 'Zorro'},
                {nombre: 'Rosa', apellido: 'Melo'},
                {nombre: 'Elmo', apellido: 'Jones'},
                {nombre: 'Gato', apellido: 'Negro'}
            ];
        }]);
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Busqueda Angular</title>
    <script src="angular.min.js"></script>
    <script src="buscar.js"> </script>
</head>
<body ng-app="busquedaAvanzada">
    <input type="text" ng-model="busqueda">
    <button>Enviar</button>

    <table ng-controller="busquedaController">
        <thead>
            <tr>
                <th>Nombre</th>
                <th>Apellido</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in lista | filter: busqueda">
                <td>{{item.nombre}}</td>
                <td>{{item.apellido}}</td>
            </tr>
        </tbody>
    </table>





</body>
</html>
    
asked by Josue Gonzalez 02.06.2017 в 15:30
source

3 answers

2

If it is not a problem to use jQuery, the solution with a json and javascript file is quite easy to implement:

The json file with the data is located on the server in a folder accessible from the web.

In the javascript file define a global object for the application where to host the data once received:

var MiApp = function(){
    this.data = [];
}

var miApp = new MiApp();

Then to find the content and save it in an object in javascript, you can download it using $.ajax . It can be done without jQuery but with jQuery it is much easier.

In the example, the findData () function makes the ajax call, so we execute it when we receive the click on the Download Data button.

Once the findData () function - which has the ajax call is executed - the data is available in myApp.data.

In the example I added a button to show the content of myApp.data.

To improve it, you could pass a parameter to the function findData () with the name to return and filter that result in the success function of ajax.

Important:
Being the file in the webserver can be consulted directly by putting the url in the browser.

And by putting a breakpoint in the ajax function you could also see all the results before being filtered.

That is, it is not for secret data :). For something like that, and removing the encryption of the channel that is another issue, you need to implement something at least in php.

EDIT 1

Example of a revised code.

Data.json file: Place it in the root directory of the webserver.

{
    "personas":[
        {"nombre":"Pepe","apellido":"Trueno"},
        {"nombre":"Kava","apellido":"Zorro"},
        {"nombre":"Rosa","apellido":"Melo"},
        {"nombre":"Elmo","apellido":"Jones"},
        {"nombre":"Gato","apellido":"Negro"}
    ]
}

Html file with javascript (and jQuery)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SOes75347</title>
</head>
<body>
<p>&quot;Mostrar los datos&quot; muestra los datos ya bajados y guardados en miApp.data. Antes de bajar los datos no hay nada cargado.</p>
<p>&quot;Buscar los datos&quot; baja el archivo json, y lo almacena en miApp.data dejándo la información disponible para ser usada.</p>
<p>Despu&eacute;s de bajar los datos, &quot;Mostrar los datos&quot; muestra los datos en un div.</p>
<br>
<button id="btnBuscar">Buscar los datos</button>
<br>
<br>
<button id="btnMostrar">Mostrar los datos</button>
<br>
<div id="divMostrar"></div>

<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>

function buscarDatos(){ //La función podría recibir un parámetro 
    //con el criterio a filtrar
    $.ajax({
        url: 'data.json',
        dataType: 'json',
        success: function(data, status, xhr) {

        //Acá podés aplicar lógica de filtrado.
        //El criterio puede ser pasado como parametro o 
        // estar previamente seteado en miApp.xxxx
        //Y así quedarte con solo los registros que queres;

        miApp.data = data; // Al especificar dataType: 'json' 
                // jQuery hace la conversión

        },
        error: function(xhr, status, error){
        //Mostrar algun eror
        }
    });
};

function mostrarDatos(){
    if(miApp.data.personas != null){
        var texto = "";
        for(var i=0; i< miApp.data.personas.length; i++){
            texto = texto + miApp.data.personas[i].nombre + " " + miApp.data.personas[i].apellido + "<br>"; 
        }
        $("#divMostrar").html(texto);
    }
}


var MiApp = function(){
    this.data = [];
}

var miApp = new MiApp();

$(document).ready(function(){
    $("#btnBuscar").click(function(e){
          var event = e || window.event;
          if(event.preventDefault){
              event.preventDefault();
          }else{
              event.returnValue = false;
          }
             buscarDatos();
          if(event.stopPropagation){
              event.stopPropagation();
          }else{
              event.cancelBubble = true;
          }
    });

    $("#btnMostrar").click(function(e){
          var event = e || window.event;
          if(event.preventDefault){
              event.preventDefault();
          }else{
              event.returnValue = false;
          }
             mostrarDatos();
          if(event.stopPropagation){
              event.stopPropagation();
          }else{
              event.cancelBubble = true;
          }
    });


});
</script>
</body>
</html>
    
answered by 02.06.2017 в 20:20
1

@josue Gonzales if you want to make a table with fictitious data I would recommend that you use this plugin is pretty good since it looks for the data according to what you want.

link

<table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>First name</th>
                <th>Last name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger</td>
                <td>Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td>Garrett</td>
                <td>Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td>Ashton</td>
                <td>Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>$86,000</td>
            </tr>
            <tr>
                <td>Cedric</td>
                <td>Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>$433,060</td>
            </tr>
            <tr>
                <td>Airi</td>
                <td>Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>$162,700</td>
            </tr>
            <tr>
                <td>Brielle</td>
                <td>Williamson</td>
                <td>Integration Specialist</td>
                <td>New York</td>
                <td>$372,000</td>
            </tr>
            <tr>
                <td>Herrod</td>
                <td>Chandler</td>
                <td>Sales Assistant</td>
                <td>San Francisco</td>
                <td>$137,500</td>
            </tr>
            <tr>
                <td>Rhona</td>
                <td>Davidson</td>
                <td>Integration Specialist</td>
                <td>Tokyo</td>
                <td>$327,900</td>
            </tr>
            <tr>
                <td>Colleen</td>
                <td>Hurst</td>
                <td>Javascript Developer</td>
                <td>San Francisco</td>
                <td>$205,500</td>
            </tr>
            <tr>
                <td>Sonya</td>
                <td>Frost</td>
                <td>Software Engineer</td>
                <td>Edinburgh</td>
                <td>$103,600</td>
            </tr>
            <tr>
                <td>Jena</td>
                <td>Gaines</td>
                <td>Office Manager</td>
                <td>London</td>
                <td>$90,560</td>
            </tr>
            <tr>
                <td>Quinn</td>
                <td>Flynn</td>
                <td>Support Lead</td>
                <td>Edinburgh</td>
                <td>$342,000</td>
            </tr>
            <tr>
                <td>Charde</td>
                <td>Marshall</td>
                <td>Regional Director</td>
                <td>San Francisco</td>
                <td>$470,600</td>
            </tr>
            <tr>
                <td>Haley</td>
                <td>Kennedy</td>
                <td>Senior Marketing Designer</td>
                <td>London</td>
                <td>$313,500</td>
            </tr>
            <tr>
                <td>Tatyana</td>
                <td>Fitzpatrick</td>
                <td>Regional Director</td>
                <td>London</td>
                <td>$385,750</td>
            </tr>
            <tr>
                <td>Michael</td>
                <td>Silva</td>
                <td>Marketing Designer</td>
                <td>London</td>
                <td>$198,500</td>
            </tr>
            <tr>
                <td>Paul</td>
                <td>Byrd</td>
                <td>Chief Financial Officer (CFO)</td>
                <td>New York</td>
                <td>$725,000</td>
            </tr>
            <tr>
                <td>Gloria</td>
                <td>Little</td>
                <td>Systems Administrator</td>
                <td>New York</td>
                <td>$237,500</td>
            </tr>
            <tr>
                <td>Bradley</td>
                <td>Greer</td>
                <td>Software Engineer</td>
                <td>London</td>
                <td>$132,000</td>
            </tr>
            <tr>
                <td>Dai</td>
                <td>Rios</td>
                <td>Personnel Lead</td>
                <td>Edinburgh</td>
                <td>$217,500</td>
            </tr>
            <tr>
                <td>Jenette</td>
                <td>Caldwell</td>
                <td>Development Lead</td>
                <td>New York</td>
                <td>$345,000</td>
            </tr>
            <tr>
                <td>Yuri</td>
                <td>Berry</td>
                <td>Chief Marketing Officer (CMO)</td>
                <td>New York</td>
                <td>$675,000</td>
            </tr>
            <tr>
                <td>Caesar</td>
                <td>Vance</td>
                <td>Pre-Sales Support</td>
                <td>New York</td>
                <td>$106,450</td>
            </tr>
            <tr>
                <td>Doris</td>
                <td>Wilder</td>
                <td>Sales Assistant</td>
                <td>Sidney</td>
                <td>$85,600</td>
            </tr>
            <tr>
                <td>Angelica</td>
                <td>Ramos</td>
                <td>Chief Executive Officer (CEO)</td>
                <td>London</td>
                <td>$1,200,000</td>
            </tr>
            <tr>
                <td>Gavin</td>
                <td>Joyce</td>
                <td>Developer</td>
                <td>Edinburgh</td>
                <td>$92,575</td>
            </tr>
            <tr>
                <td>Jennifer</td>
                <td>Chang</td>
                <td>Regional Director</td>
                <td>Singapore</td>
                <td>$357,650</td>
            </tr>
            <tr>
                <td>Brenden</td>
                <td>Wagner</td>
                <td>Software Engineer</td>
                <td>San Francisco</td>
                <td>$206,850</td>
            </tr>
            <tr>
                <td>Fiona</td>
                <td>Green</td>
                <td>Chief Operating Officer (COO)</td>
                <td>San Francisco</td>
                <td>$850,000</td>
            </tr>
            <tr>
                <td>Shou</td>
                <td>Itou</td>
                <td>Regional Marketing</td>
                <td>Tokyo</td>
                <td>$163,000</td>
            </tr>
            <tr>
                <td>Michelle</td>
                <td>House</td>
                <td>Integration Specialist</td>
                <td>Sidney</td>
                <td>$95,400</td>
            </tr>
            <tr>
                <td>Suki</td>
                <td>Burks</td>
                <td>Developer</td>
                <td>London</td>
                <td>$114,500</td>
            </tr>
            <tr>
                <td>Prescott</td>
                <td>Bartlett</td>
                <td>Technical Author</td>
                <td>London</td>
                <td>$145,000</td>
            </tr>
            <tr>
                <td>Gavin</td>
                <td>Cortez</td>
                <td>Team Leader</td>
                <td>San Francisco</td>
                <td>$235,500</td>
            </tr>
            <tr>
                <td>Martena</td>
                <td>Mccray</td>
                <td>Post-Sales support</td>
                <td>Edinburgh</td>
                <td>$324,050</td>
            </tr>
            <tr>
                <td>Unity</td>
                <td>Butler</td>
                <td>Marketing Designer</td>
                <td>San Francisco</td>
                <td>$85,675</td>
            </tr>
            <tr>
                <td>Howard</td>
                <td>Hatfield</td>
                <td>Office Manager</td>
                <td>San Francisco</td>
                <td>$164,500</td>
            </tr>
            <tr>
                <td>Hope</td>
                <td>Fuentes</td>
                <td>Secretary</td>
                <td>San Francisco</td>
                <td>$109,850</td>
            </tr>
            <tr>
                <td>Vivian</td>
                <td>Harrell</td>
                <td>Financial Controller</td>
                <td>San Francisco</td>
                <td>$452,500</td>
            </tr>
            <tr>
                <td>Timothy</td>
                <td>Mooney</td>
                <td>Office Manager</td>
                <td>London</td>
                <td>$136,200</td>
            </tr>
            <tr>
                <td>Jackson</td>
                <td>Bradshaw</td>
                <td>Director</td>
                <td>New York</td>
                <td>$645,750</td>
            </tr>
            <tr>
                <td>Olivia</td>
                <td>Liang</td>
                <td>Support Engineer</td>
                <td>Singapore</td>
                <td>$234,500</td>
            </tr>
            <tr>
                <td>Bruno</td>
                <td>Nash</td>
                <td>Software Engineer</td>
                <td>London</td>
                <td>$163,500</td>
            </tr>
            <tr>
                <td>Sakura</td>
                <td>Yamamoto</td>
                <td>Support Engineer</td>
                <td>Tokyo</td>
                <td>$139,575</td>
            </tr>
            <tr>
                <td>Thor</td>
                <td>Walton</td>
                <td>Developer</td>
                <td>New York</td>
                <td>$98,540</td>
            </tr>
            <tr>
                <td>Finn</td>
                <td>Camacho</td>
                <td>Support Engineer</td>
                <td>San Francisco</td>
                <td>$87,500</td>
            </tr>
            <tr>
                <td>Serge</td>
                <td>Baldwin</td>
                <td>Data Coordinator</td>
                <td>Singapore</td>
                <td>$138,575</td>
            </tr>
            <tr>
                <td>Zenaida</td>
                <td>Frank</td>
                <td>Software Engineer</td>
                <td>New York</td>
                <td>$125,250</td>
            </tr>
            <tr>
                <td>Zorita</td>
                <td>Serrano</td>
                <td>Software Engineer</td>
                <td>San Francisco</td>
                <td>$115,000</td>
            </tr>
            <tr>
                <td>Jennifer</td>
                <td>Acosta</td>
                <td>Junior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>$75,650</td>
            </tr>
            <tr>
                <td>Cara</td>
                <td>Stevens</td>
                <td>Sales Assistant</td>
                <td>New York</td>
                <td>$145,600</td>
            </tr>
            <tr>
                <td>Hermione</td>
                <td>Butler</td>
                <td>Regional Director</td>
                <td>London</td>
                <td>$356,250</td>
            </tr>
            <tr>
                <td>Lael</td>
                <td>Greer</td>
                <td>Systems Administrator</td>
                <td>London</td>
                <td>$103,500</td>
            </tr>
            <tr>
                <td>Jonas</td>
                <td>Alexander</td>
                <td>Developer</td>
                <td>San Francisco</td>
                <td>$86,500</td>
            </tr>
            <tr>
                <td>Shad</td>
                <td>Decker</td>
                <td>Regional Director</td>
                <td>Edinburgh</td>
                <td>$183,000</td>
            </tr>
            <tr>
                <td>Michael</td>
                <td>Bruce</td>
                <td>Javascript Developer</td>
                <td>Singapore</td>
                <td>$183,000</td>
            </tr>
            <tr>
                <td>Donna</td>
                <td>Snider</td>
                <td>Customer Support</td>
                <td>New York</td>
                <td>$112,000</td>
            </tr>
        </tbody>
    </table>

    
answered by 02.06.2017 в 15:38
1

As of HTML5 you can save data to a local database using only HTML / Javascript . There is also storage per session.

You can take a look at the documentation:

Here is a minimum example that shows how to store, read and delete data using localStorage .

You can do more advanced things, like setting the BD to work off-line, storing data in specific tables / columns, etc ... it's a matter of exploring.

SEE DEMO IN JSFIDDLE

HTML :

<input id="myData" type="text" placeholder="Escriba los datos..." />
<br />
<button onclick="createData()">Crear</button>
<button onclick="readData()">Leer</button>
<button onclick="deleteData()">Borrar</button>
<hr />
<div id="info"></div>

JS :

//array para guardar los valores
var arrData = Array();

//Identificar el elemento input
var inputData = document.getElementById('myData');

//Crear datos en local storage
function createData() {
    //Obtiene el valor actual del input
        var strDataToSave = inputData.value;
    if ((strDataToSave == null) || (strDataToSave == "")) {
        document.getElementById('info').innerHTML = "El input está vacío.";
    } else {
        //Envía valor del input al array
        arrData.push(strDataToSave);
        //Limpia el input 
        inputData.value = "";
        //Guarda el valor en el local storage llamado database agregando un espacio en blanco
        window.localStorage.setItem("database", arrData.join(" "));
        //Confirma en pantalla que los datos se guardaron
        document.getElementById('info').innerHTML = "¡Datos guardados!";
        //Limpia el mensaje de info después de 1 segundo
        setTimeout(function() {
            document.getElementById('info').innerHTML = "";
        }, 1000);

    }
}

// Leer datos
function readData() {
    //Obtiene el valor del local storage "database" por llave (key)
    if (window.localStorage.getItem("database") == null) {
        document.getElementById('info').innerHTML = "¡No hay datos!";
    } else {
        document.getElementById('info').innerHTML = 
                         window.localStorage.getItem("database");
    }
}

//Borrar datos almacenados
function deleteData() {
    //Limpia el storage
    arrData = Array();
    localStorage.clear("database");
    //Imprimir mensaje
    document.getElementById('info').innerHTML = "¡Datos borrados!";
}

CSS :

#info {
    font-size: 1.5em;
    color: red;
}
    
answered by 02.06.2017 в 16:51