Difference between revisions of "PHPAJAX"

From mi-linux
Jump to navigationJump to search
 
(5 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[Main Page]] >> [[CP2228|Web Application Development]] >> [[PHP|Workbook]] >> Ajax with jQuery
+
[[Main Page]] >> [[CP2228|Web Application Development]] >> [[PHP|Workbook]] >> Ajax with fetch()
  
== Ajax with jQuery ==
+
== Ajax with fetch==
  
Let's implement this very simple Ajax example:  
+
Let's implement this very simple example:  
* [http://mi-linux.wlv.ac.uk/~in9352/ajax/ http://mi-linux.wlv.ac.uk/~in9352/ajax/]
+
* [https://mi-linux.wlv.ac.uk/~in9352/ajax/ https://mi-linux.wlv.ac.uk/~in9352/ajax/]
 
 
== jQuery ==
 
 
 
First you'll need to include the latest stable version of jQuery. You can either:
 
* Point straight to the version hosted on the official website (quick and easy, but a bit slower).
 
* Download the library, upload it to your website via FTP, and point to your local file.
 
 
 
In both cases, the syntax is the same:
 
 
 
<pre>
 
<script src="path/to/the/file/jquery-3.1.0.min.js"></script>
 
</pre>
 
 
 
In this example we'll keep things simple and point to the hosted version:
 
 
 
<pre>
 
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
 
</pre>
 
  
 
== Client-side ==
 
== Client-side ==
Line 29: Line 11:
  
 
<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>
</pre>
 
  
The HTML is fairly simple. Note the text box, button, and blank paragraph to display the results later on.
+
<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 + ' ') ;
 +
});
 +
});
  
The bit of interest is the Ajax jQuery call, here:
 
  
<pre>
+
}
// This is the Ajax call to "getdata.php"
+
</script>
$.ajax({
 
  method: "GET",
 
  url: "getdata.php",
 
  data: { searchValue: $('#searchValue').val() }
 
})
 
 
</pre>
 
</pre>
  
In the call we specify 3 things:
+
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.
* We want to use the GET HTTP protocol (it works fine with POST too!)
 
* We want to call a file called "getdata.php". Obviously you need to create this file (see below).
 
* We pass ONE parameter to the PHP file: the value typed in the search box.
 
  
Once the response comes back from the server, this bit of code decides what to do:
+
Make sure you read the comments in the JS code.
 
 
<pre>
 
// And this handles the response
 
.done(function( response ) {
 
// Write response to our "results" element
 
$( "#results" ).html(response);
 
});
 
</pre>
 
 
 
In this case, we simply display the result ("response" variable) in our blank paragraph element ("results").
 
  
 
== Server-side ==
 
== Server-side ==
  
The server-side script is for you to complete:
+
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";
 +
else
 +
$sql = "SELECT * FROM videogames ORDER BY released_date";
 
 
// Debug message
+
// Fetch all record, convert to JSON and return
echo "Performing search for ".$searchValue."...";
+
$results = $mysqli->query($sql)->fetch_all(MYSQLI_ASSOC);
+
print(json_encode($results));
// Connect to database
 
// Build SQL statement
 
// Run SQL statement
 
// Loop through results and display
 
  
 
?>
 
?>
 
</pre>
 
</pre>
  
The only thing of interest is this line:
+
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.
 
 
<pre>
 
$searchValue = $_GET['searchValue'];
 
</pre>
 
 
 
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 ==
 
== More ==
  
Please see [http://api.jquery.com/jquery.ajax/ official documentation] for more information!
+
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.