Crafting AJAX-driven Web Applications with PHP
Hello, newbie coder! We are embarking on a fantastic journey today. Strap on your geek glasses and get ready for a fun-filled, brain-tweaking adventure!
PHP & AJAX: The Perfect Couple
Every great story contains an extraordinary duo. Batman and Robin, Peanut Butter and Jelly, Simon and Garfunkel, you get the idea. In the coding world, a dynamo duo that works seamlessly together is PHP and AJAX!
"Wait, wait! But what on earth are AJAX and PHP?" I hear you saying.
You’re right to ask! Let me decode the mystery swiftly.
PHP, or Hypertext Preprocessor in full, is an open-source scripting language, predominately used on servers to build dynamic websites. AJAX—short for Asynchronous JavaScript and XML—is a set of web development techniques used to create asynchronous web applications. These two make a reliable and efficient team.
Take a Deep Breath: How AJAX Works
Before we journey any deeper into this labyrinth, understanding how AJAX works is imperative. AJAX operates on an asynchronous data transfer model. Interpreting this from geek to normal language: webpage browsed by users doesn’t have to reload completely for every requested change. Instead, only a tiny portion of the page which contains the requested data updates.
If you ask any web developer about AJAX, they will likely swoon over its ability to enhance user-interaction in real time. But keep your insatiable curiosity intact, we’ve only just begun to understand how powerful AJAX is.
AJAX-talks with PHP in a Nutshell
PHP and AJAX make a winning team! PHP primarily works on the server-side and AJAX on the client-side. But in what other manners do they work together?
Simply put, AJAX on the front end makes requests to PHP on the server-end. The client-browser enquires ‘Hey PHP, fetch me data from the MySQL database!’ (of course, we should use polite language). The PHP on the server-end replies happily, "Anything for you, mate," gets the data, and sends it back to AJAX. AJAX, feeling like the ultimate hero, updates the specific parts of the webpage without a page reload.
The Elephant in the Room: Code, Code, and More Code
Fear not! It’s not as scary as it sounds. Here is the sneak-peek into PHP and AJAX code. Let’s continue our journey towards becoming a coding legend.
PHP Code Unveiling
Let’s pretend the PHP script is a secret coding agent given the mission to fetch data from a MySQL database. Before it rushes off on its covert mission, we need to code it first.
php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
//If connection fails, PHP dies, rest in peace mate!
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstName, lastName FROM MyTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstName"]. " " . $row["lastName"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
So, What Just Happened?
First, we created a connection to our database. Here, localhost, username, password, and myDB are replaced with your actual database information. The connection is checked, and if everything is okay, we run the SQL query, and output data. But if there is a connection error, PHP would rather die! (Not literally. Don’t panic, it’s just an error message.)
We’ve seen PHP in action, now let’s take a look at AJAX.
AJAX Code Sneak Peek
html
<!DOCTYPE html>
<html>
<body>
<div id="demo">
Let AJAX Change this Text
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
This code is a tad more straightforward. The function ;loadDoc()> triggers when you click ‘Change Content’. The magic happens when AJAX opens a file (in this case, ajax_info.txt) and updates the content in the ‘demo’ element.
That’s it! You’ve added another aspect of web development to your coder’s toolbox. Remember, practice is key in your journey to becoming a coding legend. Until next time, happy coding!