Choose a random number or name from a database

0

I have hosted a database MySQL in a Byethost free I need to call the register a name and number at random to generate a lottery.

With this code I can call my records in Javascript now I need you to call me a number or name at random.

function leer() {
    urltorequest = urlWS + "Usuario/leer";
    $.ajax({
        type: "get",
        url: urltorequest,
        async: false,
        success: function (respuesta) {
            toshow = JSON.parse(respuesta);
            cabeceraTabla = "<table class=\"table table-condensed\"><thead><tr>
                      <th>ids</th><th>Nombre</th></tr></thead><tbody>";
            pieTabla = "</tbody></table>";
            contenidoTabla = "";

            $(toshow).each(function (key, value) {
                contenidoTabla = contenidoTabla + "<tr><td>" + value.idUsuario + 
                "</td><td>" + value.nombreUsuario + "</td></tr>";
            });
            document.getElementById("respuesta").innerHTML = cabeceraTabla + 
            contenidoTabla + pieTabla;
        }
    });
}
    
asked by CHRISTIAN ALEXIS LOPEZ CHANGOL 09.01.2018 в 03:07
source

1 answer

0

Imagine that this comes from your database:

$db_names = ["Christian", "Eduardo", "José", "Patricia", "Jacinta", "Muriel"]

Which would be all the names in your database.

Then, you must obtain the length of the names, in this case to be an array:

$db_names.length // 6 nombres´

And the classic algorithm for generating random numbers is this:

Math.floor(Math.random() * (maximo - minimo + 1) + minimo)

Math.floor() rounds to the smallest integer, closest to the number.

Math.random() Generates a number between [0, 1[

In this case:

The maximum number is number of names = 6

The minimum is 0, because the array starts from index 0

Then you can ask yourself, but if it starts at index 0, then index 6 could come out and that index does not exist in the array. Correct, but remember that the +1 makes the value máximo , is inclusive, so it can be generated, then we will NOT add 1, so that it generates a number of [0, 6[

var $db_names = ["Christian", "Eduardo", "José", "Patricia", "Jacinta", "Muriel"],
        random = (max, min, inclusive) => inclusive === true ? 
        Math.floor(Math.random() * (max - min + 1) + min) :
        Math.floor(Math.random() * (max - min) + min),
    
        nameSelected = $db_names[random($db_names.length, 0, "false")];
    
   
        console.log(nameSelected);
    
answered by 09.01.2018 в 03:49