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>
1
  • Are you looking to get a value? $userCard = document.getElementById('visitorID').value - it's hard to guess without seeing your html Commented Sep 13, 2017 at 7:09

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
Thanks for the help :)
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

4 Comments

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
Okay, but implementing an AJAX is not that hard. May be useful for you.
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
We were all there before. YouTube and Google are a programmers best resources. All take a look at the documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.