I will show you how to create WordPress like add tags using Codeigniter and jQuery. This add tags tutorial example is very helpful to implement the multiple tags adding functionality for a blog.

In this example, tags are added to the textarea just by “type and press the Enter key”.

Codeigniter controller stores tags into the database table and returns response as success or failure message from the controller. As a validation step I have added one step to check if you have input at least one tag.

Prerequisites

Netbeans 8.1
XAMPP in Windows
Codeigniter 3.0.6

Configure XAMPP and Netbeans

From Netbeans IDE go to Tools->Options. Click on PHP. Now on tab “General” browse the file for “PHP 5 Interpreter”. The php interpreter file generally placed inside the <physical drive in Windows OS>:xamppphpphp.exe

Configure Codeigniter and Netbeans

Create a new PHP project in Netbeans. Then remove the index.php file from the newly created project. Now copy the extracted files from Codeigniter 3.0.6 to the newly created project directory.

Step 1. Now modify <root directory>/application/config/autoload.php file for auto-loading html, url, file, form and database.

This one time activity gives flexibility to uniformly use anywhere throughout the application without loading repeatedly.

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

Modify also <root directory>/application/config/database.php in order to establish the connection with database for performing database queries.

'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'roytuts',
'dbdriver' => 'mysqli',

Step 2. Create a controller file tagcontroller.php under ci3/application/controllers with the following source code.

The below controller class handles request and response for clients.

This class basically validates input and send the input data to the model layer where actual database operation takes place in order to save the data into database.

Finally it sends success or failure message depending on success or failure operation.

<?php

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

/**
 * Description of TagController
 *
 * @author https://roytuts.com
 */
class TagController extends CI_Controller {

    private $error;
    private $success;

    function __construct() {
        parent::__construct();
        $this->load->model('tagmodel', 'tag');
        $this->load->library('form_validation');
    }

    private function handle_error($msg) {
        $this->error .= '<p>' . $msg . '</p>';
    }

    private function handle_success($msg) {
        $this->success .= '<p>' . $msg . '</p>';
    }

    function index() {
        if ($this->input->post('add_tags')) {
            $this->form_validation->set_rules('blog_tags', 'Tags', 'trim|required');

            $blog_tags = $this->input->post('blog_tags', TRUE);

            $blog_related_tags = '';
            if (is_array(str_split($blog_tags)) && count(str_split($blog_tags)) > 2) {
                $blog_tags = $this->format_tags_keywords($blog_tags);
                $blog_related_tags = explode('$', $blog_tags);
            } else {
                $this->handle_error('Enter Tags');
            }

            if ($this->form_validation->run($this)) {
                $resp = $this->tag->add_blog_tags($blog_related_tags);
                if ($resp === TRUE) {
                    $this->handle_success('Tags are added successfully');
                }
            }

            $data['blog_tags'] = $blog_related_tags;
        }
        $data['errors'] = $this->error;
        $data['success'] = $this->success;
        $this->load->view('tags', $data);
    }

    private function format_tags_keywords($string) {
        preg_match_all('`(?:[^,"]|"((?<=\)"|[^"])*")*`x', $string, $result);
        $tags = '';
        foreach ($result as $arr) {
            $i = 0;
            foreach ($arr as $val) {
                if ($i % 2 == 1) {
                    $i++;
                    continue;
                }
                $tags .= $val . '$';
                $i++;
            }
            $tags = str_replace('[', '', $tags);
            $tags = str_replace(']', '', $tags);
            $tags = rtrim($tags, '$');
            $tags = str_replace('"', '', $tags);
            break;
        }
        return $tags;
    }

}

Step 3. Create a model file tagmodel.php under ci3/application/models with the following source code.

<?php

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

/**
 * Description of tagmodel
 *
 * @author https://roytuts.com
 */
class TagModel extends CI_Model {

    private $blog_tags = 'blog_tags';

    function __construct() {
        
    }

    function add_blog_tags($tags) {
        if (!empty($tags)) {
            foreach ($tags as $tag) {
                $tag_array = array('tag_name' => $tag);
                $this->db->insert($this->blog_tags, $tag_array);
            }
            return TRUE;
        }
        return NULL;
    }

}

Step 4. Create a view file tags.php under ci3/application/views. This view file is responsible for taking user inputs. Here you will see WordPress like add tags using codeigniter and jquery.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Create WordPress like add tags using Codeigniter</title>
        <link type="text/css" rel="stylesheet" href="<?php echo base_url(); ?>assets/css/tags/textext.core.css"/>
        <link type="text/css" rel="stylesheet" href="<?php echo base_url(); ?>assets/css/tags/textext.plugin.tags.css"/>
        <script type= 'text/javascript' src="<?php echo base_url(); ?>assets/js/jquery-1.9.1.min.js"></script>
        <script type= 'text/javascript' src="<?php echo base_url(); ?>assets/js/tags/textext.core.js"></script>
        <script type= 'text/javascript' src="<?php echo base_url(); ?>assets/js/tags/textext.plugin.tags.js"></script>
    </head>
    <body>
        <?php
        if (isset($success) && strlen($success)) {
            echo '<div style="color:green;">';
            echo $success;
            echo '</div>';
        }
        if (isset($errors) && strlen($errors)) {
            echo '<div style="color:red;">';
            echo $errors;
            echo '</div>';
        }
        if (validation_errors()) {
            echo '<div style="color:red;">';
            echo validation_errors();
            echo '</div>';
        }
        echo form_open($this->uri->uri_string(), array('id' => 'add_tags_form'));
        ?>
        <p>
            <label>Tags (type and press 'Enter')</label><br/>
            <textarea name="blog_tags" id="blog_tags" rows="5" cols="50" class="textarea"></textarea>
        </p>
        <p>
            <input type="submit" name="add_tags" id="add_tags" value="Save tags"/>
        </p>
        <?php
        echo form_close();
        ?>

        <script type="text/javascript">
            $('#blog_tags')
                    .textext({
                        plugins: 'tags',
                        tagsItems: [<?php
        if (isset($blog_tags)) {
            $i = 1;
            foreach ($blog_tags as $tag) {
                echo "'" . $tag . "'";
                if (count($blog_tags) == $i) {
                    echo '';
                } else {
                    echo ',';
                }
                $i++;
            }
        }
        ?>]
                    })
                    .bind('tagClick', function (e, tag, value, callback) {
                        var newValue = window.prompt('Enter New value', value);
                        if (newValue)
                            callback(newValue);
                    });
        </script>
    </body>
</html>

Step 5. Modify file ci3/application/config/routes.php file.

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

Step 6. If everything is fine then run the application. You will get the output in the browser.

Here you will see the final output for WordPress like add tags using codeigniter and jquery.

Here you add tags(type and press Enter key) then you will get success message as shown below:

wordpress like add tags using codeigniter and jquery

The database output

wordpress like add tags using codeigniter and jquery

Please download assets directory assets

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

Leave a Reply

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