Reputation: 23800
I have a simple javascript:
function myfunction(form)
and a form with submit button:
<input type="submit" class="btn" onclick="return myfunction(this)" onsubmit="return myfunction(this)" value="Send!">
So when the user sends the form, the function is called. In this function, for example I want to create a random number, and POST that as well with the information I have in the form.
So in the php file I read the data I want to say
$randomNumberGeneratedInTheScript = $_POST['randomNumber'];
Is this possible? Thanks..
( I do not want to generate the random number in the php file. It has to be done in JavaScript. )
Upvotes: 0
Views: 1290
Reputation: 118
You can add a hidden input in the form called randomNumber. In myFunction generate the random number and set the hidden input value to be the random number. Onsubmit can now call the function first, then submit the form normally.
Upvotes: 1
Reputation: 3307
Very simple. Use a hidden form field:
<input type="hidden" name="randomNumber" value="">
Then you can use the math function to produce a random number
var randomNumber = Math.floor(Math.random()*1000);
Note: that will produce a number bettween 1 and 1000, change the 1000 to any value you wish
Then onload or in a separate function you can call this and set the value of the hidden field
document.getElementById('randomID').value = randomNumber;
There are other methods of doing it, but for the situation you described this sounds like the most cross compatible and easiest method to use.
Upvotes: 2