Undermine2k
Undermine2k

Reputation: 1491

Variable from function not being passed to php

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

Answers (1)

John C
John C

Reputation: 8415

I could get this working following by mostly the changes suggested in the comments:

  • Make open_boosters() a function
  • Add missing = to the URL
  • Use same randnumb 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

Related Questions