JS not passing vars to php?

Discussion in 'PHP' started by ataloss, Nov 16, 2014.

  1. #1
    Hi, I'm baffled here; the two following statements from my JS
    file displays the correct values but the code to enter them
    into a table enters zeroes. I tried document.write(s) and the
    correct values were displayed.what am I missing? Thanks in advance.
    var expression = value1 + op +value2 +'='+ total;
    alert(expression);
    <?php
    include('calcbegin.html');
    $servername = "localhost";
    $username = "root";table
    $password = "cookie";
    $dbname = "homedb";
    show
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error)
    { die("Connection failed: " . $conn->connect_error); }
    $sql = "INSERT INTO calculator (purpose, value1, op, value2, total)
    VALUES ('$purpose', '$value1', '$op', '$value2', '$total')";
    if ($conn->query($sql) === TRUE)
    { echo "New record created successfully"; }
    else
    { echo "Error: " . $sql . "<br>" . $conn->error; }
    $conn->close();
    ?>
    Code (markup):

     
    Last edited by a moderator: Nov 16, 2014
    ataloss, Nov 16, 2014 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    Uhm... You can't mix js and PHP this way. PHP is run on the server, and the output is sent to the browser (or command line, or whatever you're using) - javascript run on the client (browser) and you can't use javascript variables while parsing PHP. Rethink how you're doing stuff.
    You can do the complete calculations in javascript, and send the information to a background PHP-script (which can then insert it into a MySQL-table) via AJAX, for instance.
     
    PoPSiCLe, Nov 16, 2014 IP
  3. PunctRo

    PunctRo Active Member

    Messages:
    102
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    83
    #3
    PoPSiCLe is right.
    You can't pass js variables to php like that.

    $sql = "INSERT INTO calculator (purpose, value1, op, value2, total)
    VALUES ('$purpose', '$value1', '$op', '$value2', '$total')";
    PHP:
    $value1 from your script is undefined and it's no way equal to your value1 variable from js script.It doesn't work that way.
    You can use a js ajax call that will send via post or get your js variables to a php script.
    In the php script you can access those variables via $_GET or $_POST and the use them in your db insert statement.

    I hope this helps.
     
    PunctRo, Nov 18, 2014 IP