Exploring Data Display with PHP and Ajax
In an attempt to showcase data on a PHP page using ajax, I've set up a system where a request is sent via ajax to a separate PHP file. This secondary PHP file then connects to a MySQL database and retrieves the necessary data. The goal is for users to click a button and have the retrieved data displayed on the same page without the need for a full page refresh.
Detailed Content of Files Used:
displaydata.php
- This page is visible to the client and presents the fetched data.
getData.php
- This script facilitates the connection to the MySQL database and retrieval of data.
app.js
- This file is responsible for making the ajax request.
The Challenge Faced:
Upon testing the existing code, the issue arises when clicking the button intended to trigger the ajax request results in a page reload without displaying any data.
Using Inspect Element, I observed that the requests are successfully sent with a status 200 (OK). Additionally, I placed console.log("app.js found") at the beginning of the app.js file to verify it's being read, which does display in the console; however, other console.log() statements within the function fail to appear.
Code Snippets:
app.js
function init() {
document.getElementById("Submit").addEventListener('click', ajax);
}
function ajax() {
console.log("Function started");
request = new XMLHttpRequest();
request.open('GET', 'getData.php', true);
request.onload = function() {
console.log(request);
if (request.status >= 200 && request.status < 400){
// Success!
document.getElementById("displayData").innerHTML = request.responseText;
} else {
// Error handling
}
};
request.onerror = function() {
// Connection error
};
request.send();
console.log("Request sent");
}
document.addEventListener('load', init);
displaydata.php
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="app.js"></script>
</head>
<body>
<p class='title'>Presenting udp packet data</p><hr />
<center><div class='data-window'>
<form id="getSearchNumber">
<label for="imei">IMEI of desired devices</label>
<select name="imei" id="imei">
<option value="Alldata">All Data</option>
<option value="012981000298213">012981000298213</option>
</select>
<br />
<button id="Submit">Submit</button>
</form>
<div id="displayData"></div>
</body>
</html>
I am confident in the functionality of getData.php. If you wish to review it, kindly leave a comment below.
The issue likely lies not in syntax errors but instead in the overall approach taken towards solving the problem.