我有一個非常簡單的網絡應用程序,它允許用戶輸入名和姓,並點擊提交以將名稱插入到sql數據庫中。 在表單下方有一個HTML表格,顯示數據庫表格的內容。如何使用PHP與JavaScript變量進行交互?
如果用戶單擊數據庫的任意一行,則使用以下函數將HTML元素的ID(設置爲與數據庫ID相同的值)保存到JavaScript變量中。
<!--JS Functions-->
<script>
//Determine which record is selected.
var id;
function TableSelect(el) {
id = el.id;
alert(id);
}
</script>
這裏是以下形式:
<!--HTML Form -->
<form method="post" action="index.php">
First Name: <input type="text" name="FirstName" value="">
<br><br>
Last Name: <input type="text" name="LastName" value="<?php echo $LastName;?>">
<br><br>
<input type="submit" name="submit" value="Submit">
<input type="submit" name="delete" value="Delete" onclick="Delete()">
</form>
這裏是數據的PHP處理和SQL表的輸出:
//prepare query to insert data from form into DB
if (isset($_POST['submit'])){
$query = "INSERT INTO tbl_HR_Master (First_Name, Last_Name) VALUES ('{$FirstName}', '{$LastName}') ";
$result = mysqli_query($connection, $query);
//Test if there was a query error
querycheck($result);
}//end if
//prepare query to populate table from DB
$query2 = "Select id, First_Name as 'First Name', Last_Name as 'Last Name' from tbl_HR_Master";
$result2 = mysqli_query($connection, $query2);
//Test if there was a query error
querycheck($result2);
//display table
echo "</br>";
echo "<table id=\"tbl_HR_Master\" border='1'><tr class=\"nohover\"\">";
// printing table headers
$fields_num = mysqli_num_fields($result2);
for($i=0; $i<$fields_num; $i++) {
$field = mysqli_fetch_field($result2);
echo "<td>{$field->name}</td>";
} //end for
echo "</tr>\n";
// print table rows
while($row = mysqli_fetch_row($result2))
{
echo "<tr>";
$id = $row[0];
foreach($row as $cell){
echo "<td onclick=TableSelect(this) id=". $id .">".$cell."</td>";
}//end foreach
echo "</tr>\n";
}//end while
我想要運行一個PHP函數,其從數據庫中刪除選定的記錄,然而,顯然PHP運行在服務器上,因此,我需要一些方法告訴PHP哪些記錄被選中。再一次,如果你看看我的Javascript函數,var id =最後選擇的記錄。我如何解析這個JS變量到服務器進行處理?
概括地說,要做到這一點在PHP中:
//delete selected record
if (isset($_POST['delete'])){
$query3 = "Delete from tbl_HR_Master where id = ". JS VARIABLE HERE." ";
} //end if
這給了我上次輸入的記錄,但是我需要最後一次點擊。每次功能運行時,我是否需要「發佈」? – mrgunston
作爲其他參數,如果您提交表單,它將只被轉移到後端。 或者你可以執行ajax調用,你可以看看:https://api.jquery.com/jquery.ajax/ – ScientiaEtVeritas