0

I am trying to do a select query using a javascript parameter ($userCard) obtained in the same function ( Code Below ). But an undefined variable error is given, how can pass the parameter in the query ?

<script>
function count() {
    $card = "V010"; 
    $userCard = document.getElementById('visitorID');

    if($userCard.value.length == 4){

        <?php
            $connection = connectToSql();
            $query = "SELECT * FROM visitorsystem.visitor WHERE cardNo = '$userCard' ";

            $result = mysqli_query($connection,$query)
            or die("Error in query: ". mysqli_error($connection));

            if(mysqli_fetch_assoc($result) >0)
            {   
                echo "Card in Use";
            }
        ?>

        }
}
</script>
CSchulz
  • 10,882
  • 11
  • 60
  • 114
  • Are you looking to get a value? `$userCard = document.getElementById('visitorID').value` - it's hard to guess without seeing your html – StudioTime Sep 13 '17 at 07:09

2 Answers2

2

If I read your question correctly, you are wildly miss reading the usage of PHP and Javascript. Javascript is a client language, while PHP is executed on the server.

To pass a js argument to a PHP page you have to use a form on your html and retrieve it using $_POST or $_GET variable in PHP

I recommend you go check this Difference between Javascript and PHP

m.nachury
  • 972
  • 8
  • 23
  • I am using this as i do not want the user to submit the form if the card is already in use. It sort of notifies him immediately instead of submitting the form. – Geordey Gatt Sep 13 '17 at 07:12
  • Then you will need to use Ajax, postback etc... To do the PHP / SQL request without notifying the user. However I still highly recommend you to check the link I sent you. – m.nachury Sep 13 '17 at 07:14
  • 1
    Thanks for the help :) – Geordey Gatt Sep 13 '17 at 07:18
1

You have the operations of client and server mixed up.

PHP can echo variables to static assets like .html or .js because the PHP compiler runs from the server before the file gets sent to the client.

Once the PHP was compiled and sent to the client, the only way to communicate back to the server is to:

  • Make an AJAX request
  • Refresh the page
Lars Peterson
  • 1,508
  • 1
  • 10
  • 27
  • I was trying to avoid the refresh, I will probably just do a check when it submits or create a dropdown and remove the cards in use – Geordey Gatt Sep 13 '17 at 07:18
  • Okay, but implementing an AJAX is not that hard. May be useful for you. – Lars Peterson Sep 13 '17 at 07:19
  • I tried understanding some tutorials but I didn't quite get how the responses work, I am a beginner at this and I'm basically trying everything on my own – Geordey Gatt Sep 13 '17 at 07:22
  • We were all there before. YouTube and Google are a programmers best resources. All take a look at the [documentation](http://api.jquery.com/jquery.ajax/) – Lars Peterson Sep 13 '17 at 07:40