New to PHP/MySQL here and I have been trying to learn some Ajax.
I want to return some JSON (one figure e.g 12345
) to a $variable
and echo
this variable in in a single table cell. (There may be better ways to do this however I just want to know how it's done - if at all possible!)
So far I can retrieve the JSON figure and display it within a <div id="result"></div>
using the code below, so I know the request works - I'm just stuck at passing the variable part.
My response (in Chrome) looks like this;
My code so far is;
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);
?>
My JS (contained within chartAjax.php page above)
<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>
Apologies if the code/methodology is very amateur, any help or suggestions would be welcome!