PHPAJAX
From mi-linux
Jump to navigationJump to searchMain Page >> Web Application Development >> Workbook >> Ajax with fetch()
Ajax with fetch
Let's implement this very simple example:
Client-side
First, let's have a look at the webpage itself:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Ajax demo</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <h1>Game search</h1> <form class="row g-3"> <div class="col-auto"> <input type="text" class="form-control" id="searchBox" placeholder="Keywords"> </div> </form> <p id="results"></p> </div> </body> </html> <script> // We "listen" for key pressed in our search box document.getElementById("searchBox").addEventListener("keyup", doSearch); // Function called when searching function doSearch() { // Get keyword from search box keywords = document.getElementById("searchBox").value; // Call server script, passing our keyword fetch('https://mi-linux.wlv.ac.uk/~in9352/ajax/ajax.php?search=' + keywords) // Convert response string to json object .then(response => response.json()) .then(response => { // Clear result box document.getElementById("results").innerHTML = ''; // Loop through data and add to result box response.forEach(game => { document.getElementById("results").append(game.game_name + ' ') ; }); }); } </script>
The HTML is fairly simple (I have used Bootstrap, but that's optional). Note the text box and blank paragraph to display the results later on.
Make sure you read the comments in the JS code.
Server-side
The server-side script is as follow:
<?php // Connect to database and run SQL query $mysqli = new mysqli("localhost","5cs023_user","5cs023_password","alix"); if ($mysqli -> connect_errno) { echo "Failed to connect to MySQL: " . $mysqli -> connect_error; exit(); } // Is a keyword provided in the URL? if(isset($_GET['search'])) $sql = "SELECT * FROM videogames WHERE game_name LIKE '%{$_GET['search']}%' ORDER BY released_date"; else $sql = "SELECT * FROM videogames ORDER BY released_date"; // Fetch all record, convert to JSON and return $results = $mysqli->query($sql)->fetch_all(MYSQLI_ASSOC); print(json_encode($results)); ?>
The code is very similar to our previous database example, but instead of looping and displaying each record, we fetch all records as a single object, convert it to JSON, and "dump" it with a print. This will return the JSON in the HTTP body.
More
Things to improve:
- Only trigger the search when at least 2 characters have been typed.
- Display the results in a nice list.
- Display "no results" when there is no data.