UselessGun UselessGun - 11 days ago 6
Javascript Question

How to retrieve a table made with a POST method through AJAX?

Currently working for a final project at my college, one of the things our teacher asked us was to make a table on a separate script through an AJAX POST method (making a query depending on a variable given by the user in the previous page and filling the table with the result) and then bringing that table back to the main page. However so far I haven't figured out a way to retrieve the table back correctly.

I've tried using a .load to bring back the table, but the table comes up undefined as if the variables made by the POST weren't saved. Currently I'm using an append to attach the table to my main page, but my teacher and I agree is not the right way as it keeps adding more tables to the div, and we would like only one table to appear each POST.

Here's the Main Script:

<!DOCTYPE html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#buttonone").click(function(){
var test = $("#form input[name= yourlastnamep]").val();
$.post("script_02.php",{alep: test},function(data){
$("#xmas").append(data);
$("#show").click(function(){
$("#xmas").fadeToggle();
});
});
});
});
</script>
</head>


<body>
<form id="form">
<p>Find your Last Name:</p>

<div class="form-group-register">
<label>Last Name:</label>
<input type="text" class="form-control" name="yourlastnamep">
</div>

<div class="form-group-register">
<button type="button" id="buttonone">Find me!</button>
<button type="button" id="show">Toggle!</button>
</div>
</form>
<div id="xmas"></div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>

</html>


and here's script_02.php:

<?php
$mysqli = new mysqli("localhost", "user", "password", "formysqli");
$var1 = $_POST['alep'];
$var2 = "SELECT name, middlename, lastname, age, birth from formtable where lastname = '$var1'";
$result = $mysqli->query($var2);
?>

<table border="1">
<tr>
<th>NAME</th>
<th>MIDDLE NAME</th>
<th>LASTNAME</th>
<th>AGE</th>
<th>BIRTH</th>
</tr>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['middlename']; ?></td>
<td><?php echo $row['lastname']; ?></td>
<td><?php echo $row['age']; ?></td>
<td><?php echo $row['birth']; ?></td>
</tr>
</table>


Thank you for your attention.

Answer

Instead of

$("#xmas").append(data);

use

$("#xmas").html(data);