Bookmark web page using Codeigniter and jQuery

You may also like to read:

Introduction

This tutorial shows how to bookmark a current URL. We have already built-in functionality in most of the browsers and we can bookmark a URL there but it’s also like you have to go to the menu option. The below code do the same thing just in one click on the web page. User is given a link to bookmark the current URL on any web page. This application logic is written in Codeigniter PHP framework but it’s very easy to understand the logic of the code and you can use the logic in simple PHP also. If you have any doubt or query then let me know.

Prerequisites

Apache 2.4 http server, PHP 7.3.5, Codeigniter 3.1.10, jQuery

Example with Source Code

We will look into the following steps in order to create example on bookmark web page using Codeigniter and jQuery.

Creating Project

We will create a project root directory called codeIgniter-3.1.10-bookmark-page. We will put extracted Codeigniter folders and files under the project root directory. Obviously the project context path will be codeIgniter-3.1.10-bookmark-page.

Configuring Auto-load

Now modify application/config/autoload.php file for auto-loading database, htmlurlfileform.

We need to auto-load our database and user_agent to avoid loading every time we need to use it.

$autoload['libraries'] = array('database', 'user_agent');
$autoload['helper'] = array('html', 'url', 'file', 'form');

Configuring Database

Go to location application/config/database.php file and change database parameter values as shown below. Do not forget to update accordingly if you have different values.

$db['default']['username'] = 'root'; //your database username
$db['default']['password'] = ''; //your database password
$db['default']['database'] = 'roytuts'; //your MySQL database name

Creating MySQL Table

Create a MySQL tables – bookmark in “roytuts” database.

The below table stores the bookmarked URL information into the database table.

CREATE TABLE IF NOT EXISTS bookmark (
    ip_address VARCHAR(50)    NOT NULL,
	bookmark_title VARCHAR(255)    NOT NULL,
	bookmark_url VARCHAR(255)    NOT NULL,
	browser VARCHAR(255)    NOT NULL,
	created_date DATETIME   NOT NULL
);

Creating Model Class

Create a model file bookmark_model.php under application/models directory with the below source code.

The below model class saves the bookmark info to the database table.

<?php

	if (!defined('BASEPATH'))
		exit('No direct script access allowed');

	/**
	* Description of bookmark_model
	*
	* @author https://www.roytuts.com
	*/
	class Bookmark_Model extends CI_Model {

		private $bookmark = 'bookmark';

		function __construct() {
		}

		function bookmark($title, $url) {
			$ip = $this->input->server('REMOTE_ADDR');
			$browser = $this->agent->agent_string();
			
			$data = array(
				'ip_address' => $ip,
				'bookmark_title' => $title,
				'bookmark_url' => $url,
				'browser' => $browser,
				'created_date' => date('Y-m-d H:i:s')
			);
			
			if ($this->db->insert($this->bookmark, $data)) {
				return TRUE;
			}
			
			return FALSE;
		}

	}

/* End of file bookmark_model.php */
/* Location: ./application/models/bookmark_model.php */

Creating Controller Class

Create a controller file bookmark.php under application/controllers with the following source code.

The below controller class holds the action method bookmark() and gets executed when a user triggers click on the Add to Favourite or Bookmark this page link on a view.

The view file is loaded using index() method.

<?php

	if (!defined('BASEPATH'))
		exit('No direct script access allowed');

	/**
	* Description of bookmark
	*
	* @author https://www.roytuts.com
	*/
	class Bookmark extends CI_Controller {

		function __construct() {
			parent::__construct();
			$this->load->model('bookmark_model', 'bookmark');
		}
		
		function index() {
			$this->load->view('bookmark');
		}

		function bookmark() {
			if (isset($_POST)) {
				$title = $_POST['title'];
				$url = $_POST['url'];
				
				if (strlen(trim($title)) && strlen(trim($url))) {
					$resp = $this->bookmark->bookmark($title, $url);
					
					if ($resp === TRUE) {
						echo 'Page successfully bookmarked';
					} else {
						echo 'Error occurred while bookmarking this page';
					}
				}
			}
		}
	}

/* End of file bookmark.php */
/* Location: ./application/controllers/bookmark.php */

Creating View

Create a view file bookmark.php under application/views folder.

In the view we need to place a link for allowing user click on the link to bookmark the URL. Generally the bookmark link should be placed on the template page but if you don’t use template page then don’t worry, you have to place bookmark link on every page wherever you want to place.

You need to include jQuery libraries in the head section of the HTML page.

Place the Bookmark link generally in the top section of the web page so that people can easily find the link.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Bookmark a page using CodeIgniter</title>

	<style type="text/css">

	::selection { background-color: #E13300; color: white; }
	::-moz-selection { background-color: #E13300; color: white; }

	body {
		background-color: #fff;
		margin: 40px;
		font: 13px/20px normal Helvetica, Arial, sans-serif;
		color: #4F5155;
	}

	a {
		color: #003399;
		background-color: transparent;
		font-weight: normal;
	}

	h1 {
		color: #444;
		background-color: transparent;
		border-bottom: 1px solid #D0D0D0;
		font-size: 19px;
		font-weight: normal;
		margin: 0 0 14px 0;
		padding: 14px 15px 10px 15px;
	}

	code {
		font-family: Consolas, Monaco, Courier New, Courier, monospace;
		font-size: 12px;
		background-color: #f9f9f9;
		border: 1px solid #D0D0D0;
		color: #002166;
		display: block;
		margin: 14px 0 14px 0;
		padding: 12px 10px 12px 10px;
	}

	#body {
		margin: 0 15px 0 15px;
	}

	p.footer {
		text-align: right;
		font-size: 11px;
		border-top: 1px solid #D0D0D0;
		line-height: 32px;
		padding: 0 10px 0 10px;
		margin: 20px 0 0 0;
	}

	#container {
		margin: 10px;
		border: 1px solid #D0D0D0;
		box-shadow: 0 0 8px #D0D0D0;
	}
	</style>
	
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
	<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
	<script type="text/javascript">
		$(document).ready(function() {
			$("a.bookmark").click(function(e) {
				e.preventDefault(); // this will prevent the anchor tag from going the user off to the link
				// var bookmarkUrl = this.href;
				// var bookmarkTitle = this.title;
				var bookmarkUrl = window.location.href;
				var bookmarkTitle = document.title;
				//alert(bookmarkUrl+', '+bookmarkTitle);
				var cct = $("input[name=csrf_token_name]").val();
				var token = $('#bookmark_form').serialize();
				var url = "http://localhost/codeIgniter-3.1.10-bookmark-page/index.php/bookmark/bookmark";
				var data = token + "&title=" + bookmarkTitle + "&url=" + bookmarkUrl;

				if (window.sidebar && window.sidebar.addPanel) {
					// Mozilla Firefox Bookmark, Firefox version < 23
					window.sidebar.addPanel(bookmarkTitle, bookmarkUrl,'');
					$.ajax({
						type: "POST",
						//async: false,
						url: url,
						data: data,
						dataType: "html",
						cache: false,
						csrf_token_name: cct,
						success: function(resp) {
							alert(resp);
						}
					});
				} else if(window.opera && window.print){
					// Firefox version >= 23
					$("a.bookmark").attr("href", bookmarkUrl);
					$("a.bookmark").attr("title", bookmarkTitle);
					$("a.bookmark").attr("rel", "sidebar");
					$.ajax({
						type: "POST",
						//async: false,
						url: url,
						data: data,
						dataType: "html",
						cache: false,
						csrf_token_name: cct,
						success: function(resp) {
							alert(resp);
						}
					});
					return true;		
				} else if ((window.external && ('AddFavorite' in window.external))) { // For IE Favorite
					window.external.AddFavorite(bookmarkUrl, bookmarkTitle);
					$.ajax({
						type: "POST",
						//async: false,
						url: url,
						data: data,
						dataType: "html",
						cache: false,
						csrf_token_name: cct,
						success: function(resp) {
							alert(resp);
						}
					});
				} else { // for other browsers which does not support
					alert('Your browser does not support this bookmark action');
					if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1){ //chrome
						alert("In order to bookmark press " + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL') + "+D.")
					}
					if ((window.sidebar && ! (window.sidebar instanceof Node)/*/Firefox/i.test(navigator.userAgent)*/)){ //Firefox
						alert("In order to bookmark press " + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL') + "+D.")
					}
					return false;
				}
			});
		});
	</script>
</head>
<body>

<div id="container">
	<h1>Welcome to CodeIgniter!</h1>

	<div id="body">
		<form id="bookmark_form" name="bookmark_form" action="#" method="post">
			<?php echo form_hidden($this->security->get_csrf_token_name(), $this->security->get_csrf_hash()); ?>
			<a class="bookmark" style="color: #0077b3;" href="#">Add to Favourite or Bookmark this page</a>
		</form>
		
		<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>

		<p>If you would like to edit this page you'll find it located at:</p>
		<code>application/views/bookmark.php</code>

		<p>The corresponding controller for this page is found at:</p>
		<code>application/controllers/Bookmark.php</code>

		<p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p>
	</div>

	<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo  (ENVIRONMENT === 'development') ?  'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
</div>

</body>
</html>

We have used below line to use hidden input field in our bookmark form:

<?php echo form_hidden($this->security->get_csrf_token_name(), $this->security->get_csrf_hash()); ?>

The above hidden input field with security token value. This is needed only when we have changed the default value(FALSE) for csrf_protection to TRUE at location application/config/config.php.

This jquery part where actually the URL gets bookmarked and data gets saved to the database. We need the jquery code when a user clicks on the Bookmark link to bookmark the URL.

var url = "http://localhost/codeIgniter-3.1.10-bookmark-page/index.php/bookmark";

We have codeIgniter-3.1.10-bookmark-page segment in the above URL, it means it is the root directory of the project. We have bookmark segment in the URL, it means it is the controller name and after the controller name there is no more segment, so it means that the controller bookmark executes default action method index.

var cct = $("input[name=csrf_token_name]").val();
var token = $('#bookmark_form').serialize();

In the above code snippets we are fetching security token value. This is needed only when we have changed the default value(FALSE) for csrf_protection to TRUE for below line at location application/config/config.php.

$config['csrf_protection'] = FALSE;

Configuring Route

Modify file application/config/routes.php file.

$route['default_controller'] = 'bookmark';

Testing the Application

Chrome (Version – 75.0.3770.90)

Chrome does not support bookmarking using jQuery/JavaScript, so you need to press Ctrl+D to bookmark the page.

bookmark web page using codeigniter and jquery

Internet Explorer (Version – 11.0.125)

When you click on the link Add to Favourite or Bookmark this page:

bookmark page codeigniter

When successfully bookmarked, you will see below alert box:

bookmark page codeigniter

When you check the Favorite, then you will see the page has been bookmarked.

bookmark page codeigniter

Firefox/Mozilla (Version – 67.0.1)

bookmark a page

Source Code

You can download source code.

Thanks for reading.

Bookmark web page using Codeigniter and jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top