add text editor in HTML form Codeigniter

Cause of add text editor in HTML form Codeigniter

This problem of add text editor in HTML form Codeigniter is most common to the person who is working on making websites or web applications. Let’s understand this problem with help of an example. Imagine if you are working on a website and you want to add the data of any template in your database. It will help you to remember the template and design at any later date. You have made the table with all possible columns but then too you are getting an error while adding data to it. 

The code for getting the current content from the console is:

 

$("#saveContent").click(function(){
console.log($("#trumbowyg-demo").html());

});

 

This code results in an error message while running it. The error message below is the message one can get on his/her screen:

 

 

Solution

One of the easiest solutions for the above problem is that one can send a straightforward post with a single variable to a controller method. It accepts it and enters the variable into the database.

Action methods are public methods found in the Controller class. Incoming browser requests are mainly handled by the controller and its action method. It also retrieves the required model data and returns pertinent results.

The code can work in two languages that are JavaScript and PHP. The code in JavaScript is:

 

$("#saveContent").click(function () {
    var content = $("#trumbowyg-demo").html();
    $.ajax({
        type: 'POST',
        url: '/somecontroller/add',
        data: {
            content: content
        },
        dataType: 'json',
        success: function (data) {
            if (data.status == 'error') {
                alert('An error occured: ' + data.msg);
            } else {
                alert('Success: ' + data.msg)
            }
        }
    });
});

 

The PHP code is like this:

 

class Somecontroller extends CI_Controller {

    public function add() {

        $content = $this->input->post('content');

        if (empty($content)) {
            echo json_encode(array('status' => 'error', 'msg' => 'Content field cannot be empty!'));
            exit;
        }

        // db functions should be move to a model
        // probably would be a good idea to filter $content somehow
        // all the db insert does is escape
        $this->db->insert('sometable', array('somefield' => $content));

        echo json_encode(array('status' => 'success', 'msg' => 'Item added with id: ' . $this->db->insert_id()));
        exit;
    }

}

 

 

Also Read: what is Attribute error and how to solve it?

 

 

Share this post

One thought on “add text editor in HTML form Codeigniter

Leave a Reply

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