Difference between revisions of "PHPAJAX"

From mi-linux
Jump to navigationJump to search
Line 65: Line 65:
 
</pre>
 
</pre>
  
The HTML is fairly simple (I have used Bootstrap, but that's optional). Note the text box, button, and blank paragraph to display the results later on.
+
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.
 
Make sure you read the comments in the JS code.

Revision as of 15:31, 12 September 2023

Main 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();
	}
	$sql = "SELECT * FROM videogames WHERE game_name LIKE '%{$_GET['search']}%' ORDER BY released_date";
	$results = $mysqli->query($sql)->fetch_all(MYSQLI_ASSOC);
	print(json_encode($results));

?>

The only thing of interest is this line:

$searchValue = $_GET['searchValue'];

It simply reads the search value passed from the Ajax call. If you use the POST protocol instead of GET in your Ajax call, then replace $_GET by $_POST!

Once you have obtained the value, simply perform a database search, as covered in an earlier week.

More

Things to improve:

  • Only trigger the search when at least 2 characters have been typed.
  • Display the results in a nice list.