Difference between revisions of "PHPAJAX"

From mi-linux
Jump to navigationJump to search
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 DoSearch()
+
    <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="DoSearch();">
 
 
<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, button, 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:
 
 
 
<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").
+
Make sure you read the comments in the JS code.
  
 
== Server-side ==
 
== Server-side ==
  
The server-side script is for you to complete:
+
The server-side script is as follow:
  
 
<pre>
 
<pre>
 
<?php
 
<?php
+
 
// Retreive value passed from Ajax call
+
// Connect to database and run SQL query
$searchValue = $_GET['searchValue'];
+
$mysqli = new mysqli("localhost","5cs023_user","5cs023_password","alix");
+
if ($mysqli -> connect_errno) {
// Debug message
+
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
echo "Performing search for ".$searchValue."...";
+
  exit();
+
}
// Connect to database
+
$sql = "SELECT * FROM videogames WHERE game_name LIKE '%{$_GET['search']}%' ORDER BY released_date";
// Build SQL statement
+
$results = $mysqli->query($sql)->fetch_all(MYSQLI_ASSOC);
// Run SQL statement
+
print(json_encode($results));
// Loop through results and display
 
  
 
?>
 
?>
Line 123: Line 101:
 
== 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.

Revision as of 15:30, 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, button, 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.