Search code examples
javascriptjquerytampermonkey

Trying to send random number with post request


I'm trying to send a post request with a random generated number. My script generates the random number fine. My problem is that it's not sending the generated number correctly. It only sends the first part. Which is 100 and not the generated number.

You can see where I've added the variable(number) to the request shown below in the code.

Math.floor((Math.random() * 100) + 1);
var number = [[100,Math.floor((Math.random() * 100) + 1)]]

window.onkeydown = function(event) {
if (event.keyCode === 84) {
console.log('started');
$.post("/draw.php?ing=_index", {
                l: parseInt(number), //<<<< MY ERROR IS HERE!!
                w: ("15"),
                c: ("#0000ff"),
                o: ("100"),
                f: ("1"),
                _: ("false")
            })
console.log(number)
}
};

I've put MY ERROR IS HERE!! where the error may be happening at. So right now it's sending that post request data of l: as [[100]] I would like it to send with the generated number. Making the l: data like [[100,75]] (As a example.)


Solution

  • Instead of parseInt, you can use JSON.stringify to get your array as string:

    l: JSON.stringify(number), // => "[[100,75]]"
    

    Edit: Define number inside the function:

    window.onkeydown = function(event) {
      var number = [[100,Math.floor((Math.random() * 100) + 1)]];
      ...