這裏新增了PHP/MySQL,我一直在嘗試學習一些Ajax。Ajax和PHP將數據返回到表單元格
我想在一個表格單元格返回一些JSON(一張圖e.g 12345
)到$variable
和echo
這個變量英寸(可能有更好的方法來做到這一點,但我只是想知道它是如何完成的 - 如果可能的話)
到目前爲止,我可以檢索JSON圖並使用下面的代碼在<div id="result"></div>
中顯示它,所以我知道請求的作品 - 我只是在傳遞可變部分。
我的回覆(在Chrome中)看起來像這樣;
我的代碼到目前爲止;
chartAjax.php
<form method="post" id="search">
<input type="text" id="date" name="date">
<input type="submit" value="Submit">
</form>
<div id="result"></div> <!-- this successfully displays the figure on submit -->
<table id="datatable" class="table">
<tbody>
<tr>
<th>Data</th>
<td>{NEED TO echo the $result here}</td> <!-- stuck here -->
</tr>
</tbody>
</table>
monthConn.php
<?php
/* set header type to json */
header('Content-Type: application/json');
/* array to pass back data */
$data = array();
/* get date from form submit */
if (isset($_POST['date']) && !empty($_POST['date'])){$date = $_POST['date'];}
/* Create a prepared statement */
$stmt = $conn -> prepare("SELECT count(*) FROM transactions WHERE TimeStamp >= ?");
/* Bind parameters */
$stmt -> bind_param("s", $date);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($data);
/* fetch values */
$stmt->fetch();
/* close conn */
$stmt->close();
echo json_encode($data);
?>
我JS(包含上述chartAjax.php頁面內)
<script>
$(document).ready(function() {
$('#search').submit(function(event) {
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $(this).serialize();
ajaxRequest= $.ajax({
url: "monthConn.php",
type: "post",
data: values,
success: function(response, data) {
if(data == "success") {
$("#result").html(response); //add response to results div
}
},
});
});
});
</script>
如果代碼/方法是非常業餘的道歉,歡迎任何幫助或建議!
你的數據/響應是什麼樣的? – Jai
這不是json,這只是文字。 json是像'{key:value}'這樣的關鍵值對。 – Jai