Timothy Fisher Timothy Fisher - 5 months ago 13x
PHP Question

Ajax GET Request is duplicating page

I have been reading up on Ajax and am following along on W3Schools.com. I am using Ajax/PHP/MySQL. So far I've gotten the request to successfully query my database based on a button selection, however it's reprinting my entire page when I click on one of the buttons.

Here is the Ajax code:

function statusShow(status) {
if(status == "") {
document.getElementById("exams").innerHTML = "";
} else {
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("exams").innerHTML = xmlhttp.responseText;
xmlhttp.open("GET", "rspamanager.php?st="+status, true);

And this is part of the PHP that is printing a table

if(isset($_GET["st"])) {
$st = mysqli_real_escape_string($connection, $_GET["st"]);
} else {
// default status
$st = "open";
if($connection) {
$query = "SELECT * FROM exams WHERE status = '{$st}'";
$sth = mysqli_query($connection, $query);
while ($result = mysqli_fetch_assoc($sth)) {
etc ...

This is all in the same php file "rspamanager.php".

EDIT: Button code:

<button onclick="statusShow(this.value)" value="open" class="status_open">Open</button>
<button onclick="statusShow(this.value)" value="closed" class="status_closed">Complete</button>


Thank you for everyone's help, it was a silly mistake. I ended up putting all of the code to generate the table in a separate file to call and it worked. Not because of the separate file, it just made me understand the request a bit better.

xmlhttp.open("GET", "ajax.php?st="+st, true);

My problem was that I had my PHP script that was being called hard-coded into the page, so it was written, and then written again when called. Copy/pasting all the hard-coded PHP script into a separate file fixed this and made it easier to understand.

Julie mentioned that the script was simply giving me a full page instead of just the section I needed which made the solution click with me.

Also, thank you Bryan for the suggestion to use no-cache options.