lundi 8 mai 2017

math.random number inside a for loop in JavaScript always generates same value

I have a simple HTML web page with some basic form input elements. It's purpose is to perform multiple AJAX requests to a simple HTTP API that processes transactions, and requires a first name, last name and transaction value. This webpage is a tool to perform multiple API requests so as to generate some example data.

The following input fields on the HTML page are of relevance:

  1. Number of events. Input type = number. Purpose = lets the user define how many API calls to perform.
  2. Min transaction value. Input type = number. Purpose = lets the user specify the minimum value of the transaction.
  3. Max transaction value. Input type = number. Purpose = lets the user specify the maximum value of the transaction.
  4. Generate random user details. Input type = checkbox. Purpose: if this is selected a random first and last name will be chosen from an array i've defined and passed with the API call. This works very nicely.

Once the user fills these fields, several API calls will be made (as per #1 above). Each API call passes a transaction_value. I've written a basic function to generate a random number that falls between the max and min numbers the user defines (#2 and #3 above).

The issue i'm facing is that while the first name and last name are correctly randomized, the transaction value seems to be generated outside of the loop, and within the loop, is always evaluating to the same number.

If i look at the developer console the console.log statement I use to output the random transaction value occurs first, then the API calls are generated, and all contain the same value. See the ajax.js file i have linked to my index.html below:

$(document).ready(function() {

    function doAPI(currentEvent,first_name,last_name,account_login,account_email,transaction_amount) {
    //Craft API request
        var orgID = $('input[name=orgID]').val();
        var sessionid = $('input[name=sessionid]').val();
        var policy = $('input[name=policy]').val();
        apiurl = "http://ift.tt/2pYgugE";
        apiurl += orgID;
        apiurl += "&policy=" + policy;

        $.ajax({
            type        : 'GET', // define the HTTP verb to use (GET or POST)
            url         : apiurl,// the url where we want to POST
            dataType    : 'html', // server response data type (html, json, xml)
            cache       : true
        })

            // using the done promise callback
            .done(function(data) {

                // handle errors and validation messages
                if ( ! data.type == "success") {

                    alert('Error Detected. Please view developer console for more info.'); // for now we'll just alert the user
                    // handle errors for name ---------------
                    // if (data.errors.numEvents) {
                    //     $('#numEventsGroup').addClass('has-error'); // add the error class to show red input
                    //     $('#numEventsGroup').append('<div class="help-block">' + data.errors.numEvents + '</div>'); // add the actual error message under our input
                    // }

                } else {
                    // success

                    var JSONResponse = $.parseJSON(data)

                    responseContents += JSONResponse.api_call_datetime;
                    responseContents += " request_result:";
                    responseContents += JSONResponse.request_result;

                    $('#console').append(responseContents);

                }// /else

            });// .done(function(data))

    } // doAPI function

    // random function
    function randomEl(list) {
        var i = Math.floor(Math.random() * list.length);
        return list[i];
    }

    // select names
    function selectElementContents(el) {
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }

    // name definitions
    var firstnames = ["James", "John", "Robert"];
    var lastnames = ["Smith", "Johnson", "Williams", "Jones"];

    // random number generator
    function randomNumberFromRange(min,max) {
        return Math.floor(Math.random()*(max-min+1)+min);
    }    

    // process the form
    $('form').submit(function(event) {

        var numEvents = $('input[name=numEvents]').val();

        for (i = 0; i < numEvents; i++) {

            event.preventDefault();

            if($("#randaccountdetails").prop('checked') == true) {
                var first_name = randomEl(firstnames);
                var last_name = randomEl(lastnames);
                var account_login = first_name.charAt(0) + last_name;
                var account_email_unencoded = account_login + "@email.com";
                var account_email = encodeURIComponent(account_email_unencoded);
            }// if randaccountdetails checked

            if( $("#txnmin") && $("#txnmax") ) {
                // grab the min and max from the form
                var minNumber = $('input[name=txnmin]').val();
                var maxNumber = $('input[name=txnmax]').val();

                //convert from string to num
                var minNumberInt = Number(minNumber);
                var maxNumberInt = Number(maxNumber);                    

                //generates the random number
                var transaction_amount = randomNumberFromRange(minNumberInt, maxNumberInt);
                console.log(transaction_amount);           
            }          

            currentEvent = i;
            doAPI(currentEvent,first_name,last_name,account_login, account_email,transaction_amount);
            // stop the form from submitting the normal way and refreshing the page
            event.preventDefault();
        }// /for

    }); //form submit

}); // doc ready




Aucun commentaire:

Enregistrer un commentaire