Difference between revisions of "6CS028 Workshop - Ajax"

From mi-linux
Jump to navigationJump to search
 
(63 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[Main Page]] >> [[6CC001|Advanced Web Technologies]] >> [[6CC001 - Workbook|Workbook]] >> Week 05
+
[[Main Page]] >> [[6CS028|Advanced Web Development]] >> [[6CS028 - Workbook|Workbook]] >> Week 04 - Ajax
  
Today we are going to use Ajax to create a simple Live Search. There are 3 simple steps:
+
'''Important''': this is a CodeIgniter example, but it is easily adaptable to Laravel.
  
* Step 1 – Create the web page
+
== The JSON data ==
* Step 2 – Create the client-side script (JavaScript)
 
* Step 3 – Create the server-side script (PHP)
 
  
== Prototype JavaScript Framework ==
+
First, let's create a page that will output JSON data from our existing "news" database table, like this:
 
+
* https://mi-linux.wlv.ac.uk/~in9352/ci4/public/index.php/ajax/get/hello
Let’s use the [http://www.prototypejs.org/ Prototype JavaScript Framework] so we don't have to type too much JavaScript code :)
 
* Download the [http://www.prototypejs.org/ Prototype JavaScript Framework]
 
* Upload it to your mi-linux account (in the same folder as your web pages)
 
* Don't forget to set its permissions to "readable" and "writeable" by all.
 
 
 
== Step 1 – Create the web page ==
 
 
 
First we obviously need to create our web page. Let’s keep it nice and simple:
 
  
 +
Create a '''new''' controller called '''Ajax.php''', with the following code:
 
<pre>
 
<pre>
<HTML>
+
<?php
  <HEAD>
 
    <TITLE>Test Ajax</TITLE>
 
    <SCRIPT type="text/javascript" src="prototype.js"></SCRIPT>
 
    <SCRIPT type="text/javascript" src="ajax.js"></SCRIPT>
 
  </HEAD>
 
  <BODY>
 
    <INPUT type="text" id="a_name">
 
    <INPUT type="button" value="Check name" onclick="send_request();">
 
    <DIV id="div_result"></DIV>
 
  </BODY>
 
</HTML>
 
</pre>
 
  
In our head section:
+
namespace App\Controllers;
* A link to the Prototype JavaScript Framework (see previous section)
 
* A link to our Ajax JavaScript code
 
  
On the page itself:
+
use App\Models\NewsModel;
* A simple text box
 
* A button that will trigger the Ajax code (located in the file below)
 
* A "div_result" element, in which the Ajax response will be displayed
 
  
== Step 2 – Create the client-side script (JavaScript) ==
+
class Ajax extends BaseController
 
 
This file implements the client-side part of our Ajax transaction:
 
* It reads the name typed in the text box
 
* Checks that it is not blank
 
* Creates an Ajax object (this will only work if you have downloaded the Prototype library)
 
* Creates a Request, passing in our "Name" parameter, and defining what should happen when the response comes back:
 
 
 
<pre>
 
// ajax.js
 
 
 
function send_request()
 
 
{
 
{
  // Get user input
+
public function get($slug = null)
  name = document.getElementById("a_name").value;
+
{
 
+
$model = model(NewsModel::class);
  // Check if name was provided
+
$data = $model->getNews($slug);
  if(name!="")
 
  {
 
    // Create and execute Ajax request
 
    new Ajax.Request('ajax.php',
 
      {
 
        method:'get',
 
        parameters: {name: name},
 
       
 
        // What should happen when the response comes back
 
        onSuccess: function(transport){
 
          var response = transport.responseText || "no response text";
 
          document.getElementById("div_result").innerHTML = response;
 
        },
 
       
 
        // What should happen if the request fails
 
        onFailure: function(){ alert('Something went wrong...') }
 
      });
 
  
  }
+
print(json_encode($data));
  else
+
}
  {
+
  var  sh = document.getElementById("div_result");
 
  sh.innerHTML = "Please enter value";   
 
  }
 
 
}
 
}
 
</pre>
 
</pre>
 +
Note: it is very similar to our previous news controller. The function above selects a given news items from our model (as per before), but converts the data to JSON and simply prints it to the browser.
  
== Step 3 – Create the server-side script (PHP) ==
+
== The Ajax call ==
 +
Next, we need to write some JavaScript that will "fetch" data from the URL above.
  
Now all we need is the server-side part of our Ajax transaction. It’s a simple PHP file that reads the parameters passed in the URL, and then queries the database. I will let you implement the database access… this example features a “fake” database check (a simple if statement).
+
In your '''existing overview.php''' view, make the following changes:
  
 +
Add a container paragraph (maybe right at the top for now), that will be used to display the data coming back from the request:
 
<pre>
 
<pre>
<?
+
<p id="ajaxArticle"></p>
  // ajax.php
+
</pre>
  
  // Get value coming from request
+
Next, add a button for each article, that calls the JavaScript code, passing the current article's slug:
  $name = $_GET['name'];
+
<pre>
 +
<p><button onclick="getData('<?= esc($news_item['slug'], 'url') ?>')">View article via Ajax</button></p>
 +
</pre>
 +
Note: the above should be inside the foreach loop, right after the existing "view article" link.
  
  // Connect to DB
+
Finally, add the JavaScript block at the bottom of the file:
 
+
<pre>
  // Check if name exists in table
+
<script>
 
+
function getData(slug) {
  if($name=="Alix")
+
    echo("This name is in the database");
+
// Fetch data
  else
+
fetch('https://mi-linux.wlv.ac.uk/~in9352/ci4/public/ajax/get/' + slug)
    echo("This name is NOT in the database :(");
+
 
+
  // Convert response string to json object
  //Close connection
+
  .then(response => response.json())
 +
  .then(response => {
  
?>
+
// Copy one element of response to our HTML paragraph
 +
document.getElementById("ajaxArticle").innerHTML = response.title + ": " + response.text;
 +
  })
 +
  .catch(err => {
 +
 +
// Display errors in console
 +
console.log(err);
 +
});
 +
}
 +
</script>
 
</pre>
 
</pre>
 +
Notes:
 +
* you will have to change the URL in the fetch statement, to match yours.
 +
* the document.getElementById("ajaxArticle").innerHTML allows you to write to the HTML element specified earlier. You could have more than one!
 +
* you might eventually wish to move this to an external JS file, as it's more efficient and tidy.
  
== All done ==
+
Here is mine:
 
+
* [https://mi-linux.wlv.ac.uk/~in9352/ci4/public/index.php/newsajax https://mi-linux.wlv.ac.uk/~in9352/ci4/public/index.php/newsajax]
Your live search should now work… Here is a [http://mi-linux.wlv.ac.uk/~in9352/ajax/page.html working example] on my account.
+
* Try pressing the various "View article via Ajax" buttons, and see how the article is displayed at the top.
 +
* Look in the developer tools / network tab, and note how each button triggers an HTTP request behind the scenes! Look at their preview.

Latest revision as of 17:12, 9 March 2023

Main Page >> Advanced Web Development >> Workbook >> Week 04 - Ajax

Important: this is a CodeIgniter example, but it is easily adaptable to Laravel.

The JSON data

First, let's create a page that will output JSON data from our existing "news" database table, like this:

Create a new controller called Ajax.php, with the following code:

<?php

namespace App\Controllers;

use App\Models\NewsModel;

class Ajax extends BaseController
{
	public function get($slug = null)
	{
		$model = model(NewsModel::class);
		$data = $model->getNews($slug);

		print(json_encode($data));
	}
	
}

Note: it is very similar to our previous news controller. The function above selects a given news items from our model (as per before), but converts the data to JSON and simply prints it to the browser.

The Ajax call

Next, we need to write some JavaScript that will "fetch" data from the URL above.

In your existing overview.php view, make the following changes:

Add a container paragraph (maybe right at the top for now), that will be used to display the data coming back from the request:

<p id="ajaxArticle"></p>

Next, add a button for each article, that calls the JavaScript code, passing the current article's slug:

<p><button onclick="getData('<?= esc($news_item['slug'], 'url') ?>')">View article via Ajax</button></p>

Note: the above should be inside the foreach loop, right after the existing "view article" link.

Finally, add the JavaScript block at the bottom of the file:

<script>
	function getData(slug) {
		
		// Fetch data
		fetch('https://mi-linux.wlv.ac.uk/~in9352/ci4/public/ajax/get/' + slug)
			
		  // Convert response string to json object
		  .then(response => response.json())
		  .then(response => {

			// Copy one element of response to our HTML paragraph
			document.getElementById("ajaxArticle").innerHTML = response.title + ": " + response.text;
		  })
		  .catch(err => {
			
			// Display errors in console
			console.log(err);
		});
	}
</script>

Notes:

  • you will have to change the URL in the fetch statement, to match yours.
  • the document.getElementById("ajaxArticle").innerHTML allows you to write to the HTML element specified earlier. You could have more than one!
  • you might eventually wish to move this to an external JS file, as it's more efficient and tidy.

Here is mine: