从php文件发送变量到jquery文件

时间:2016-04-21 09:41:25

标签: javascript php jquery ajax

我正在尝试将位于php文件中的php变量传递给单独的JavaScript文件。我试图将输入函数中php文件末尾的变量传递给名为public partial class Form1 : BaseForm { public Form1() { InitializeComponent(); } } $message的jQuery变量。

这是我到目前为止所处的位置:

chat.php

$username

这是我的jquery文件

<?php
    //form data
    $username = $_POST['username'];
    $password = $_POST['password'];
    //sql server connection credentials
    $servername = "localhost";
    $serverusername = "suser11";
    $serverpassword = "suser11";
    $databasename = "chat_database";
    // Create connection
    $conn = new mysqli($servername, $serverusername, $serverpassword, $databasename);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully<br /><br />";
    $username = $conn->real_escape_string($username);
    $password = $conn->real_escape_string($password);
    $sql = "SELECT Salt FROM users WHERE Username='$username'";
    $result = $conn->query($sql);
    while($row = $result->fetch_assoc()) {
        $salt = $row["Salt"];
    }
    $sql = "SELECT * FROM users WHERE Username='$username' AND Password=MD5('$password$salt')";
    $result = $conn->query($sql);
    if($result->num_rows === 0) {
        $conn->close(); //close the db connection
        header('Location: login.html'); //redirect to login.html
    } else {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "UserID: " . $row["user_id"]. " - Name: " . $row["username"]. "<br />";
        }
    }
    // Close the database connection
    $conn->close();
?>
<textarea id="myChat" type="text" style="width:500px; height:500px;"></textarea>
<br/>
<br/>
<input id="myText" name="myText"/>
<input type="hidden" value="<?php echo $username; ?>"/>
<button id="add">
    <b>Add to chat</b>
</button>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

在php中你可以通过: 只需替换您的代码:

// output data of each row
        while($row = $result->fetch_assoc()) {
            echo "UserID: " . $row["user_id"]. " - Name: " . $row["username"]. "<br />";
        }

以下代码:

while($row = $result->fetch_assoc()) {
   echo $row["user_id"]."||".$row["username"];
}

和ajax:

$.ajax({ 
       type: "POST",
       url:'myprocess.php',
       data:{'xml': $xmlString},
       dataType:'text/xml',
       success: function(data){ 
              details = data.split("||");
              username = details[0];
              password = details[1];
       }
});