Integrate CKEditor in Html Page using JavaScript
Wall Script
Follow Me:
Monday, April 18, 2016

Integrate CKEditor in Html Page using JavaScript

CKEditor is a rich web text editor, which can be used inside your HTML web pages. This HTML text editor allows many of the powerful editing functions found on desktop editors like Microsoft Word to your web. This is featured with many advantages like preparing your mail content, creating your blogs and so on. This post also explains you how to further modify or use your text editor in many ways, which may include show / hide buttons, control the buttons, etc,.

Integrate CKEditor in Html Page using JavaScript


Download Script     Live Demo

The tutorial contains three folders called ckeditor, js and css with PHP files.
ckeditor
---- ckeditor.js
---- config.js // ckeditor configuration file
.......
.......
js
-- jquery.min.js
index.php
ajaxPublish.php
config.php
blogPost.php
blogClass.php

Blog Table
Blog table contains all the blog post details.
CREATE TABLE blog(
bid INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(300),
body TEXT,
created INT,
statusCode ENUM('0','1','2') DEFAULT '1');

Enable PDO extension for PHP, find this in php.ini configuration file.

index.php
Contains javascript code. $("#publish").click(function(){}- here publish is the ID name of the submit button. Using $("#postTitle").val() and editor.getData() calling subject and text area values. Always include CKEDITOR.replace('postBody') after textarea tag.
<script src="ckeditor/ckeditor.js"></script>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#publish").click(function(){
var postTitle = $("#postTitle").val();
var editorData = editor.getData();
var postBody=editorData.replace(/&nbsp;/gi,' ');
var dataString = 'title='+ postTitle +'&body='+postBody;
$.ajax({
type: "POST",
url: "ajaxPublish.php",
data: dataString,
cache: false,
beforeSend: function(){},
success: function(bid)
{
window.location.replace('blogPage.php?bid='+bid);
}
});
return false;
});
})
</script>
//HTML Code
Add New Post
<input type="text" id="postTitle" class="inputText" placeholder="Post title"  />
<textarea id="postBody" name="postBody"></textarea>
<input type="submit" value="Publish" class="wallButton" id="publish"/>
<script>
var editor=CKEDITOR.replace('postBody');
</script>

ckeditor/config.js
CKEditor configuration file, here you can enable or disable CKEditor options.
CKEDITOR.editorConfig = function(config) {
config.htmlEncodeOutput = false; //HTML encode
config.entities = false;
config.toolbarGroups = [
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
{ name: 'forms', groups: [ 'forms' ] },
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
{ name: 'links', groups: [ 'links' ] },
{ name: 'insert', groups: [ 'insert' ] },
{ name: 'styles', groups: [ 'styles' ] },
{ name: 'colors', groups: [ 'colors' ] },
{ name: 'tools', groups: [ 'tools' ] },
{ name: 'others', groups: [ 'others' ] },
{ name: 'about', groups: [ 'about' ] }
];
config.removeButtons = 'Outdent,Indent,CreateDiv,Flash,Table,HorizontalRule,Smiley,SpecialChar,PageBreak,Iframe,Styles,FontSize,ShowBlocks,About,Subscript,Superscript,Find,Replace,Cut,Copy,Paste,PasteText,PasteFromWord,Templates,Radio,Checkbox,Form,TextField,SelectAll,Select,Textarea,Button,ImageButton,HiddenField,Scayt,RemoveFormat,BidiLtr,BidiRtl,Language,Anchor,Source,Save,Templates,NewPage,Preview,Print,Undo,Redo';
};

config.php
Database connection configuration file, here you have to modify username, password and database details. If you are using other database modify PDO() driver connection value.
<?php
session_start();
/* DATABASE CONFIGURATION */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'databasename');
define("BASE_URL", "http://localhost/PHPLoginHash/"); // Eg. http://yourwebsite.com

function getDB()
{
$dbhost=DB_SERVER;
$dbuser=DB_USERNAME;
$dbpass=DB_PASSWORD;
$dbname=DB_DATABASE;
try {
$dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbConnection->exec("set names utf8");
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
?>

blogClass.php
This class contains two methods blogPublish and blogDetails.
<?php
class blogClass
{
/* Blog Publish */
public function blogPublish($title,$body)
{
try{
$db = getDB();
$created=time();
$stmt = $db->prepare("INSERT INTO blog(title,body,created) VALUES(:title,:body,:created)");
$stmt->bindParam("title", $title,PDO::PARAM_STR) ;
$stmt->bindParam("body", $body,PDO::PARAM_STR) ;
$stmt->bindParam("created", $created,PDO::PARAM_INT) ;
$stmt->execute();
$bid=$db->lastInsertId();
$db = null;
return $bid;
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

/* Blog Details */
public function blogDetails($bid)
{
try{
$db = getDB();
$stmt = $db->prepare("SELECT * FROM blog WHERE bid=:bid");
$stmt->bindParam("bid", $bid,PDO::PARAM_INT) ;
$stmt->execute();
$blogData=$stmt->fetch(PDO::FETCH_OBJ);
$db = null;
return $blogData;
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

}
?>

ajaxPublish.php
Contains PHP code, this will help to insert blog data into blog table.
<?php
include 'config.php';
if(trim($_POST['title']) && trim($_POST['body']))
{
include 'blogClass.php';
$blogClass = new blogClass();
$title=$_POST['title'];
$body=$_POST['body'];
echo $blogClass->blogPublish($title,$body);
}
?>

blogPage.php
Using this you can display existing blog title and body, based on blog row id.
<?php
include 'config.php';
if($_GET['bid']>0)
{
include 'blogClass.php';
$blogClass = new blogClass();
$bid=$_GET['bid'];
$blogData=$blogClass->blogDetails($bid);
}
else
{
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CKEditor Blog Page</title>
<link href="style.css" rel="stylesheet"/>
</head>
<body id="main">
<div>
<h1><?php echo $blogData->title; ?></h1>
<div>
<?php echo $blogData->body; ?>
</div>
</div>
</body>
</html>
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


8 comments:

  1. Thanks for sharing this. but there is bug in it, when we select a word and change its format (H1 -> H2, H3 ) then whole paragraph will be formatted.

    ReplyDelete
  2. Interesting and well written example on integrating CKEditor. Thanks..

    ReplyDelete
  3. Sir there are many Editors available on the web but a problem is that we cant upload any file to the server by using them So please You must add this feature in Your current API

    ReplyDelete
  4. can you tell me about how to clear the ckeditor after form is submitted.

    ReplyDelete
  5. Thank you, you have solved my problem .
    must admit, it is a very decent work.

    ReplyDelete
  6. hey can you also add the ckFinder

    ReplyDelete
  7. Is there any script or jquery or ajax to load table data on a php page at real-time?

    ReplyDelete

Make in India