Difference between revisions of "6CS028 Workshop - Ajax"

From mi-linux
Jump to navigationJump to search
 
(53 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[Main Page]] >> [[6CC001|Advanced Web Technologies]] >> [[6CC001 - Workbook|Workbook]] >> Week 06
+
[[Main Page]] >> [[6CS028|Advanced Web Development]] >> [[6CS028 - Workbook|Workbook]] >> Week 04 - Ajax
  
Today we are going to use Ajax to create a simple jQuery Live Search in Code Igniter:
+
'''Important''': this is a CodeIgniter example, but it is easily adaptable to Laravel.
  
* Step 1 – Create the data controller/view
+
== The JSON data ==
* Step 2 – Create the web page controller/view
 
  
== Include jQuery ==
+
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
Please note that we will be using the [http://jquery.com/ jQuery] library, so you need to include it in your <head> section. You can do this by adding the following <script> line to your templates/header.php file:
 
  
 +
Create a '''new''' controller called '''Ajax.php''', with the following code:
 
<pre>
 
<pre>
<html>
+
<?php
<head>
 
  <title><?php echo $title ?> - CodeIgniter 2 Tutorial</title>
 
  <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
 
</head>
 
<body>
 
<h1>CodeIgniter 2 Tutorial</h1>
 
</pre>
 
 
 
== Step 1 – Create the data controller/view ==
 
  
First we need to create the page (i.e. model + controller + view) that will return the Ajax data.
+
namespace App\Controllers;
  
For now let's keep our controller simple:
+
use App\Models\NewsModel;
  
<pre>
+
class Ajax extends BaseController
<?php
 
class Ajax extends CI_Controller
 
 
{
 
{
 +
public function get($slug = null)
 +
{
 +
$model = model(NewsModel::class);
 +
$data = $model->getNews($slug);
  
  public function getdata($param = '')
+
print(json_encode($data));
  {
+
}
      // Get data from db
+
      $data['ajaxdata'] = "Search result for $param";
 
 
 
      // Pass data to view
 
      $this->load->view('ajax/index', $data);
 
  }
 
 
}
 
}
 
</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.
  
As you can see we are using dummy data. You'll have to add the model part yourselves (as per [http://ellislab.com/codeigniter/user-guide/tutorial/news_section.html News section tutorial] on the Code Igniter website!
+
== The Ajax call ==
 +
Next, we need to write some JavaScript that will "fetch" data from the URL above.
  
Note that we are NOT including the header and footer views, as our Ajax data will be embedded in an existing page (see later).
+
In your '''existing overview.php''' view, make the following changes:
  
Our view is very simple:
+
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>
 +
<p id="ajaxArticle"></p>
 +
</pre>
  
 +
Next, add a button for each article, that calls the JavaScript code, passing the current article's slug:
 
<pre>
 
<pre>
<p><?=$ajaxdata?></p>
+
<p><button onclick="getData('<?= esc($news_item['slug'], 'url') ?>')">View article via Ajax</button></p>
</p>
+
</pre>
 +
Note: the above should be inside the foreach loop, right after the existing "view article" link.
  
It simply displays the data passed in yb the controller.
+
Finally, add the JavaScript block at the bottom of the file:
 +
<pre>
 +
<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 => {
  
You should now be able to browse to your ajax controller:
+
// Copy one element of response to our HTML paragraph
[[http://mi-linux.wlv.ac.uk/~in9352/ci/index.php/ajax/getdata/ http://mi-linux.wlv.ac.uk/~in9352/ci/index.php/ajax/getdata/]]
+
document.getElementById("ajaxArticle").innerHTML = response.title + ": " + response.text;
 
+
  })
You can pass it a term to be searched in the URL:
+
  .catch(err => {
[[http://mi-linux.wlv.ac.uk/~in9352/ci/index.php/ajax/getdata/batman http://mi-linux.wlv.ac.uk/~in9352/ci/index.php/ajax/getdata/batman]]
+
 +
// Display errors in console
 +
console.log(err);
 +
});
 +
}
 +
</script>
 +
</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.
  
== Step 2 – Create the web page controller/view ==
+
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]
 +
* 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: