[英]How do I show the PHP variable value in the JavaScript pop-up?
我有以下腳本。 用戶將在URL中傳遞一個數字值(例如123)作為參數,應用程序將從MySQL加載/獲取該值並將其顯示在文本區域中。
例如,在URL中輸入“ example.com/index.php?id=123”將從數據庫中提取第123條記錄,並將其顯示在文本區域中。 一切似乎都正常,但是我想在提交表單時顯示“源”表的最后一行/ id。 因此,與其顯示“已保存!” 在彈出窗口中,它應該顯示類似“ 124”(或最后更新的行/編號)的內容。
index.php:
<?php
include('connect-db.php');
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT content FROM source WHERE id=$id") or die(mysqli_error());
$row = mysql_fetch_array($result);
if($row)
{
$submit_date = date("Ymd");
$content = $row['content'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
//
// show the last id here!
//
function(data){ alert("Saved!"); }
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
Submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
//
// Show the variable (last_id) value in the JavaScript above!
//
$last_id = mysql_insert_id();
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
連接數據庫:
<?php
$server = 'localhost';
$user = 'domdom';
$pass = 'password@123';
$db = 'domdom';
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
?>
請注意,我不需要有關PDO或MySQLi的任何建議,這在當前並不重要。 但是,歡迎提供有關改進安全性/ SQL查詢的任何建議。 謝謝。
我將嘗試分兩個部分進行回答:
[1] PHP方面:在“ isset($ _ GET ['id'])”部分中,僅返回要填寫的文本區域的內容。 假設在您的數據庫中,是123->“星期五”。 只需返回字符串“星期五”。
[2]客戶端:請勿“提交”表格。 調用JS函數,然后在其中創建XmlHttpRequest,並將該請求作為AJAX請求發送到服務器。 獲得返回值后,請檢查返回值並填充HTML文本區域。
如果您認為此方法適合您並且需要更多詳細信息,請告訴我。 我在許多網站上都這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.