Difference between revisions of "PHPAJAX"

From mi-linux
Jump to navigationJump to search
 
(17 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[Main Page]] >> [[CP2228|Web Application Development]] >> [[PHP|Workbook]] >> Template Engines
+
[[Main Page]] >> [[CP2228|Web Application Development]] >> [[PHP|Workbook]] >> Ajax with fetch()
  
Let's implement this very simple Ajax example: [http://mi-linux.wlv.ac.uk/~in9352/ajax/]
+
== Ajax with fetch==
  
== jQuery ==
+
Let's implement this very simple example:
 +
* [https://mi-linux.wlv.ac.uk/~in9352/ajax/ https://mi-linux.wlv.ac.uk/~in9352/ajax/]
  
 
== Client-side ==
 
== Client-side ==
 +
 +
First, let's have a look at the webpage itself:
  
 
<pre>
 
<pre>
<html>
+
<!doctype html>
<head>
+
<html lang="en">
<title>Ajax example</title>
+
  <head>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
+
    <meta charset="utf-8">
<script>
+
    <meta name="viewport" content="width=device-width, initial-scale=1">
function DoDearch()
+
    <title>Ajax demo</title>
{
+
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet">
// This is the Ajax call to "getdata.php"
+
  </head>
$.ajax({
+
  <body>
  method: "GET",
+
    <div class="container">
  url: "getdata.php",
+
<h1>Game search</h1>
  data: { searchValue: $('#searchValue').val() }
+
<form class="row g-3">
})
+
  <div class="col-auto">
+
<input type="text" class="form-control" id="searchBox" placeholder="Keywords">
// And this handles the response
+
  </div>
.done(function( response ) {
+
</form>
// Write response to our "results" element
 
$( "#results" ).html(response);
 
});
 
}
 
</script>
 
</head>
 
<body>
 
<h1>Ajax example</h1>
 
Enter value: <input type="text" id="searchValue">
 
<input type="button" value="Search" onclick="DoDearch();">
 
 
<p id="results"></p>
 
<p id="results"></p>
</body>
+
</div>
 +
 +
  </body>
 
</html>
 
</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>
 
</pre>
 
</pre>
 +
 +
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 ==
 
== Server-side ==
 +
 +
The server-side script is as follow:
  
 
<pre>
 
<pre>
 
<?php
 
<?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();
 +
}
 
 
// Retreive value passed from Ajax call
+
// Is a keyword provided in the URL?
$searchValue = $_GET['searchValue'];
+
if(isset($_GET['search']))
+
$sql = "SELECT * FROM videogames WHERE game_name LIKE '%{$_GET['search']}%' ORDER BY released_date";
// Debug message
+
else
echo "Performing search for ".$searchValue."...";
+
$sql = "SELECT * FROM videogames ORDER BY released_date";
 
 
// Connect to database
+
// Fetch all record, convert to JSON and return
// Build SQL statement
+
$results = $mysqli->query($sql)->fetch_all(MYSQLI_ASSOC);
// Run SQL statement
+
print(json_encode($results));
// Loop through results and display
 
  
 
?>
 
?>
 
</pre>
 
</pre>
 +
 +
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.

Latest revision as of 16:36, 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();
	}
	
	// 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.