Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to pass JavaScript variables to PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 163
    Comment on it

    Many a times we got stuck in a case or situation where we have to pass JavaScript variables to PHP using a hidden input in a form. The solution for this situation is:


    Solution:We cannot pass variable values from the current page javascript to the current page PHP code. PHP code runs on the server side and it is unaware about what is going on on the client side. So, for passing JavaScript variables to PHP we have to submitting form on GET or POST methods.

    1. <doctype html="">
    2. <html>
    3. <head>
    4. <title>My Test Form</title>
    5. </head>
    6.  
    7. <body>
    8. <form method="POST">
    9. <p>Please, choose the salary id to proceed result:</p>
    10. <p>
    11. <label for="salarieids">SalarieID:</label>
    12. <?php
    13. $query = "SELECT * FROM salarie";
    14. $result = mysql_query($query);
    15. if ($result) :
    16. ?>
    17. <select id="salarieids" name="salarieid">
    18. <?php
    19. while ($row = mysql_fetch_assoc($result)) {
    20. echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
    21. }
    22. ?>
    23. </select>
    24. <?php endif ?>
    25. </p>
    26. <p>
    27. <input type="submit" value="Sumbit my choice"/>
    28. </p>
    29. </form>
    30.  
    31. <?php if isset($_POST['salaried']) : ?>
    32. <?php
    33. $query = "SELECT * FROM salarie WHERE salarieid = " . _POST['salarieid'];
    34. $result = mysql_query($query);
    35. if ($result) :
    36. ?>
    37. <table>
    38. <?php
    39. while ($row = mysql_fetch_assoc($result)) {
    40. echo '<tr>';
    41. echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
    42. echo '</tr>';
    43. }
    44. ?>
    45. </table>
    46. <?php endif?>
    47. <?php endif ?>
    48. </body>
    49. </html>
    50. </doctype>

    By this way we will pass JavaScript variables to PHP.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: