-2
我想將位於php文件中的php變量傳遞給單獨的JavaScript文件。我試圖將輸入函數中php文件末尾的變量傳遞給名爲$message
和$username
的jQuery變量。將變量從php文件發送到jquery文件
這是我在哪裏至今:
chat.php
<?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>
這裏是我的jQuery文件
$(document).ready(function() { //start 1
//alert("hello world, jQuery is working");
setInterval(function(){$("#myChat").load("chat.txt")},100); //update the textarea with the text file contents every 10th of a second
var $message = '';
var $username = '';
$('#add').click(function(){ // start 2
var $message = $('#myText').val();
var $username = $('$username').val();
//alert("Got the message");
$.ajax({ // start 3
type: "POST",
url:'myprocess.php',
data:{'xml': $xmlString},
dataType:'text/xml',
//success: function(r){ // start 4
//alert('Got it');
//}, // end 4
//error: function (xhr, desc, err) {
//console.log(xhr);
//console.log("Details: " + desc + "\nError: " + err);
//alert ("Error: " + err);
//}
}); // end 3
$('#myText').val(""); //clears value of text box on click of button with id=add
}); // end 2
//forming proper xml
$xmlString ='<?xml version="1.0" encoding="ISO-8859-1"?>';
$xmlString += '<message><user>' + username + '</user><text>' + $message + '</text></message>';
}); // end 1
哪裏包括PHP?在我目前的PHP代碼結束? – neost3
我編輯了答案。 –
由於某些原因,仍然無法正常工作。我是否也想用上面的代碼替換當前的ajax?這是我試過的,它不起作用。 – neost3