Reputation: 1491
I'm having some trouble passing in a variable from my javascript function to my php page. open_boosters returns a random variable from an array which I want to pass to site3.php. I know the PHP code get's executed first but how can I pass these variables without the user having to click anything?
> Main.html
<p id="generatenumbers"></p>
<script>
var open_boosters = function()
{
var i, j;
var array=[];
for(i=0; i < 13; i++)
{
(array[i] = Math.floor(Math.random()*14)+16);
for(j=0;j<i;j++)
{
while(array[i]==array[j])
{
(array[i]= Math.floor(Math.random()*14)+16);
}
}
return array[i];
}
}
window.addEventListener('DOMContentLoaded', function ()
{
var randnumb = open_boosters();
document.getElementById("generatenumbers").innerHTML=open_boosters();
document.getElementById("randImg").src = "site3.php?rndNum"+randnumb;
}, false);
</script>
site3.php
<?php
$mysqli=mysqli_connect('localhost','root','','draftdb');
if (!$mysqli)
die("Can't connect to MySQL: ".mysqli_connect_error());
$stmt = $mysqli->prepare("SELECT display.PICTURE_ID
FROM cards
INNER JOIN display ON cards.DISPLAY_ID = display.DISPLAY_ID
WHERE display.DISPLAY_ID=? AND cards.CARD_TYPE ='rare'" );
$displayid = isset($_GET['randnumb'])? $_GET['randnumb'] : false;
//echo "Number: ".$displayid." ";
$stmt->bind_param("i", $displayid);
$stmt->execute();
$stmt->bind_result($image);
$stmt->fetch();
//header("Content-Type: image/jpeg");
echo $image;
?>
Upvotes: 0
Views: 128
Reputation: 8415
I could get this working following by mostly the changes suggested in the comments:
open_boosters()
a function=
to the URLrandnumb
variable for both the getElementById
set functions<p id="generatenumbers"></p>
<img src="" id="randImg" />
<script>
function open_boosters()
{
var i, j;
var array=[];
for(i=0; i < 13; i++)
{
(array[i] = Math.floor(Math.random()*14)+16);
for(j=0;j<i;j++)
{
while(array[i]==array[j])
{
(array[i]= Math.floor(Math.random()*14)+16);
}
}
return array[i];
}
}
window.addEventListener('DOMContentLoaded', function ()
{
var randnumb = open_boosters();
document.getElementById("generatenumbers").innerHTML=randnumb;
document.getElementById("randImg").src = "site3.php?rndNum="+randnumb;
}, false);
</script>
The random number is then available to the site3.php script as $_GET['rndNum']
(not $_GET['randnumb']
).
Upvotes: 2