Wordpress
Create Ajax Comments System in WordPress
In this article, we are going to discuss about How to create an ajax comments system in Wordpress. WordPress started in 2003 with a single bit of code to enhance the typography of everyday writing and with fewer users than you can count on your fingers and toes. Since then it has grown to be the largest self-hosted blogging tool in the world, used on millions of sites and seen by tens of millions of people every day.
Here is the code for creating ajax comments system in WordPress.
var commentform = $('#commentform');
// find the comment form
commentform.prepend('<div id="comment-status" ></div>');
// add info panel before the form to provide feedback or errors
var statusdiv = $('#comment-status');
var commentsdiv = $('.commentlist');
// define the infopanel
commentform.submit(function() {
//serialize and store form data in a variable
var formdata = commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl = commentform.attr('action');
//Post Form with data
$.ajax({
type : 'post',
dataType: 'json',
url : formurl,
data : formdata,
error : function(XMLHttpRequest, textStatus, errorThrown) {
statusdiv.html('<p class="wdpajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
},
success : function(data, textStatus) {
console.log(data);
if (data.comment_approved === "1"){
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
commentsdiv.prepend('<li class="comment byuser comment-author-admin bypostauthor even thread-even depth-1" id="comment-1"><div class="comment-body" id="comment-body-1"><div class="comment-avatar-box"><div class="avb"><a href="http://vidibase.com/members/' + data.comment_author + '/" rel="nofollow"><img src="http://i0.wp.com/vidibase.com/wp-content/plugins/buddypress/bp-core/images/mystery-man.jpg" class="avatar user-1-avatar avatar-60 photo" width="60" height="60" alt="Avatar Image"></a></div></div><div class="comment-content"><div class="comment-meta"><p><a href="http://vidibase.com/members/' + data.comment_author + '/" rel="nofollow">' + data.comment_author + '</a> said on <a href="#"><span class="time-since">Just now</span></a></p></div><div class="comment-entry"><p>' + data.comment_content + '</p></div><div class="comment-options"></div><div class="clear"> </div></div></li>');
}else{
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
commentform.find('textarea[name=comment]').val('');
}
}
});
return false;
});
Add the below code in functions.php file
add_action('comment_post', 'ajaxify_comments',20, 2);
function ajaxify_comments($comment_ID, $comment_status){
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
//If AJAX Request Then
switch($comment_status){
case '0':
//notify moderator of unapproved comment
wp_notify_moderator($comment_ID);
case '1': //Approved comment
$commentdata=&get_comment($comment_ID, ARRAY_A);
$post=&get_post($commentdata['comment_post_ID']);
wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
echo json_encode($commentdata);
break;
default:
echo "error";
}
exit;
}
}
Here is the code for creating ajax comments system in WordPress.
var commentform = $('#commentform');
// find the comment form
commentform.prepend('<div id="comment-status" ></div>');
// add info panel before the form to provide feedback or errors
var statusdiv = $('#comment-status');
var commentsdiv = $('.commentlist');
// define the infopanel
commentform.submit(function() {
//serialize and store form data in a variable
var formdata = commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl = commentform.attr('action');
//Post Form with data
$.ajax({
type : 'post',
dataType: 'json',
url : formurl,
data : formdata,
error : function(XMLHttpRequest, textStatus, errorThrown) {
statusdiv.html('<p class="wdpajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
},
success : function(data, textStatus) {
console.log(data);
if (data.comment_approved === "1"){
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
commentsdiv.prepend('<li class="comment byuser comment-author-admin bypostauthor even thread-even depth-1" id="comment-1"><div class="comment-body" id="comment-body-1"><div class="comment-avatar-box"><div class="avb"><a href="http://vidibase.com/members/' + data.comment_author + '/" rel="nofollow"><img src="http://i0.wp.com/vidibase.com/wp-content/plugins/buddypress/bp-core/images/mystery-man.jpg" class="avatar user-1-avatar avatar-60 photo" width="60" height="60" alt="Avatar Image"></a></div></div><div class="comment-content"><div class="comment-meta"><p><a href="http://vidibase.com/members/' + data.comment_author + '/" rel="nofollow">' + data.comment_author + '</a> said on <a href="#"><span class="time-since">Just now</span></a></p></div><div class="comment-entry"><p>' + data.comment_content + '</p></div><div class="comment-options"></div><div class="clear"> </div></div></li>');
}else{
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
commentform.find('textarea[name=comment]').val('');
}
}
});
return false;
});
Add the below code in functions.php file
add_action('comment_post', 'ajaxify_comments',20, 2);
function ajaxify_comments($comment_ID, $comment_status){
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
//If AJAX Request Then
switch($comment_status){
case '0':
//notify moderator of unapproved comment
wp_notify_moderator($comment_ID);
case '1': //Approved comment
$commentdata=&get_comment($comment_ID, ARRAY_A);
$post=&get_post($commentdata['comment_post_ID']);
wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
echo json_encode($commentdata);
break;
default:
echo "error";
}
exit;
}
}
PHP CMS Frameworks
September 28, 2014
Read more →
CakePHP
Steps to add file download option in Cakephp
In this article, we are going to discuss about How to add file download option in CakePHP. CakePHP is an open source web application framework. It follows the Model-View-Controller (MVC) approach and is written in PHP, modeled after the concepts of Ruby on Rails, and distributed under the MIT License. CakePHP uses well-known software engineering concepts and software design patterns, as Convention over configuration, Model-View-Controller, Active Record, Association Data Mapping, and Front Controller.
To add the file download option in CakePHP, include the below action in your controller, from which controller you want to execute the download
function file_download($file_name = null) {
$this->autoRender = false;
$this->set('fileName', $file_name);
header('Content-Type: application/download');
$url = WWW_ROOT.DS.'fileFolderName'.DS.$file_name;
header("Content-Disposition: attachment; filename=".basename($url));
header("Content-Length: " . filesize($url));
$fp = fopen($url, "r");
fpassthru($fp);
fclose($fp);
}
Now add the following link in your View file from where you want to download the file
echo $this->Html->link(__('Download', true), array('controller' => 'mycontroller','action' => 'pdf_download', $file['file_name']));
/* Here $file['file_name'] is the name of your file. */
To add the file download option in CakePHP, include the below action in your controller, from which controller you want to execute the download
function file_download($file_name = null) {
$this->autoRender = false;
$this->set('fileName', $file_name);
header('Content-Type: application/download');
$url = WWW_ROOT.DS.'fileFolderName'.DS.$file_name;
header("Content-Disposition: attachment; filename=".basename($url));
header("Content-Length: " . filesize($url));
$fp = fopen($url, "r");
fpassthru($fp);
fclose($fp);
}
Now add the following link in your View file from where you want to download the file
echo $this->Html->link(__('Download', true), array('controller' => 'mycontroller','action' => 'pdf_download', $file['file_name']));
/* Here $file['file_name'] is the name of your file. */
PHP CMS Frameworks
September 24, 2014
Read more →
CodeIgniter
CodeIgniter - Change the URL and Email as Hyperlink automatically
In this article, we are going to discuss about How to change the URL and Email as Hyperlink in CodeIgniter. We might have seen plain text get converted to hypertext when we type it. For example, In gtalk when we type www.phpcmsframework.com it automatically changes as a hyperlink and point to http://www.phpcmsframework.com, Same way, when we type an email address it is automatically converted to mailto:phpcmsframework@gmail.com.
These kind of conversion can be made using PHP string replace function. We have to check the whole string where it has the url or email address, then we have to replace the url with anchor tag.
In CodeIgniter the easiest way to do it is to use the URL helper. First step is to load the URL helper.
$this->load->helper('url');
Then the next thing to do is to use a function
auto_link();
This function makes our life easier. We have to pass the string that we need to find for url and email.
$string = "This is a sample text and its url is www.phpcmsframework.com";
echo auto_link($string);
The output of the above code is Today I visited a useful blog about web development and its url is www.phpcmsframework.com
The same way email id is also auto linked. We can also restrict the automation only to url or email. This can be done by
echo auto_link($string,'email');
echo auto_link($string,'url');
In case if we want the link to open in a new tab, we can do it by adding a third parameter which can be either TRUE or FALSE.
echo auto_link($string, 'both', TRUE);
Here second parameter 'both' indicates that both 'email' and 'url' has to be automatically converted to hypertext.
These kind of conversion can be made using PHP string replace function. We have to check the whole string where it has the url or email address, then we have to replace the url with anchor tag.
In CodeIgniter the easiest way to do it is to use the URL helper. First step is to load the URL helper.
$this->load->helper('url');
Then the next thing to do is to use a function
auto_link();
This function makes our life easier. We have to pass the string that we need to find for url and email.
$string = "This is a sample text and its url is www.phpcmsframework.com";
echo auto_link($string);
The output of the above code is Today I visited a useful blog about web development and its url is www.phpcmsframework.com
The same way email id is also auto linked. We can also restrict the automation only to url or email. This can be done by
echo auto_link($string,'email');
echo auto_link($string,'url');
In case if we want the link to open in a new tab, we can do it by adding a third parameter which can be either TRUE or FALSE.
echo auto_link($string, 'both', TRUE);
Here second parameter 'both' indicates that both 'email' and 'url' has to be automatically converted to hypertext.
PHP CMS Frameworks
September 17, 2014
Read more →
Symfony
Procedure to Manually authenticate user in Symfony 2 framework
In this article, we are going to discuss about How to manually authenticate users in Symfony 2 PHP Framework. Normally in each and every framework authencation in handled automatically. Sometimes, however you may want to perform authentication manually from the controller.
Imagine implementing automated login for a user upon visiting a URL like: /autologin/{secret}. I am not considering here the security of such a solution – you are discourage to do it this way, unless the information available for this kind of "logins" is not confidential.
Here is a fragment from my security.yml:
security:
firewalls:
secured_area:
pattern: ^/
form_login:
check_path: /login_check
login_path: /login
The actual authentication is very straight-forward. Since I'm redirecting at the end of request, I don't even need the user to be authenticated in this action. All that is needed is to persist the information about authenticated user to the session. This means storing serialized class that implements TokenInterface. Normally this is done by Symfony framework in ContextListener. In my scenario I'm using form login that uses UsernamePasswordToken, so in short here is what I need to do:
Pay attention to "secured_area" string – it matches the firewall name from the security.yml and is used to create the token and when creating a session key.
/**
* @Route("/autologin/{secret}")
*/
public function autologinAction($secret) {
$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('MiedzywodzieClientBundle:Reservation');
$result = $repository->matchLoginKey($secret);
if (!$result) {
return $this->render('MiedzywodzieClientBundle:Default:autologin_incorrect.html.twig');
}
$result = $result[0];
$token = new UsernamePasswordToken($result, $result->getPassword(), 'secured_area', $result->getRoles());
$request = $this->getRequest();
$session = $request->getSession();
$session->set('_security_secured_area', serialize($token));
$router = $this->get('router');
$url = $router->generate('miedzywodzie_client_default_dashboard');
return $this->redirect($url);
}
Imagine implementing automated login for a user upon visiting a URL like: /autologin/{secret}. I am not considering here the security of such a solution – you are discourage to do it this way, unless the information available for this kind of "logins" is not confidential.
Here is a fragment from my security.yml:
security:
firewalls:
secured_area:
pattern: ^/
form_login:
check_path: /login_check
login_path: /login
The actual authentication is very straight-forward. Since I'm redirecting at the end of request, I don't even need the user to be authenticated in this action. All that is needed is to persist the information about authenticated user to the session. This means storing serialized class that implements TokenInterface. Normally this is done by Symfony framework in ContextListener. In my scenario I'm using form login that uses UsernamePasswordToken, so in short here is what I need to do:
- Find user
- Create the Token
- Store Token in the session
Pay attention to "secured_area" string – it matches the firewall name from the security.yml and is used to create the token and when creating a session key.
/**
* @Route("/autologin/{secret}")
*/
public function autologinAction($secret) {
$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('MiedzywodzieClientBundle:Reservation');
$result = $repository->matchLoginKey($secret);
if (!$result) {
return $this->render('MiedzywodzieClientBundle:Default:autologin_incorrect.html.twig');
}
$result = $result[0];
$token = new UsernamePasswordToken($result, $result->getPassword(), 'secured_area', $result->getRoles());
$request = $this->getRequest();
$session = $request->getSession();
$session->set('_security_secured_area', serialize($token));
$router = $this->get('router');
$url = $router->generate('miedzywodzie_client_default_dashboard');
return $this->redirect($url);
}
PHP CMS Frameworks
September 10, 2014
Read more →
Drupal
Steps to configure google maps with nodes in Drupal
In this article, we are going to discuss about How to configure google maps with nodes in Drupal. Drupal is a free software package that allows you to easily organize, manage and publish your content, with an endless variety of customization.
Step 1: Install Locations Module
Step 2: Install Gmap Module
Step 3: Enable Gmap Location Module Which is part of Gmap Module.
Step 4: Set the Google Map Key Here admin/settings/gmap
Step 5: Go here admin/settings/location/main and select default country and check Use a Google Map to set latitude and longitude
Step 6: Go to content type edit tab and select Locations Collapsible tab, under that go to Number Of Locations and set min, max, Number of locations that can be added at once as 1,1,1 respectively
Step 7: Go to your nodes click on edit and you can see location settings, there give the address and longitude and latitude which you can pick from map or you can set. Longitude and Latitude are very important to locate a node in map
Step 8: Save the node.
Step 9: admin/settings/gmap_location go here, under node map select marker action as open link.
Step 10: Now go to map/node you can see all your nodes here.
Step 11: If you want to enable map for nodes go to blocks, enable the block called Location Map
That's it you are done.
Step 1: Install Locations Module
Step 2: Install Gmap Module
Step 3: Enable Gmap Location Module Which is part of Gmap Module.
Step 4: Set the Google Map Key Here admin/settings/gmap
Step 5: Go here admin/settings/location/main and select default country and check Use a Google Map to set latitude and longitude
Step 6: Go to content type edit tab and select Locations Collapsible tab, under that go to Number Of Locations and set min, max, Number of locations that can be added at once as 1,1,1 respectively
Step 7: Go to your nodes click on edit and you can see location settings, there give the address and longitude and latitude which you can pick from map or you can set. Longitude and Latitude are very important to locate a node in map
Step 8: Save the node.
Step 9: admin/settings/gmap_location go here, under node map select marker action as open link.
Step 10: Now go to map/node you can see all your nodes here.
Step 11: If you want to enable map for nodes go to blocks, enable the block called Location Map
That's it you are done.
PHP CMS Frameworks
September 03, 2014
Read more →
Symfony
Integrate Zend Framework components with Symfony2
In this article, we are going to discuss about How to integrate Zend framework components with Symfony2 framework. Symfony2 is a full stack of PHP Development Framework by using the features of PHP 5.3. Zend Framework is a component library that is super a lot and have a MVC layer. When 2 Framework is incorporated, imagine how powerful right?
Hm ... of course the principle of use at will (Use What you Need, Forget Everything Else) should still be used. The need for very complete component in Zend Framework can be used in Symfony with me registers the Zend Framework components in Symfony autoloader Framewok.
Zend Framework library that will we 'list'-right in Symfony2, we have saved in the folder \FrameworkSymfonyApp\vendor\namapackage as follows:
Well, after that, we document in its Symfony2 autoloader:
$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
...
));
$loader->registerPrefixes(array(
....
'Zend_' => __DIR__.'/../vendor/zf'
));
Ok, next is testing time. I will try to use his class Validator Zend Framework, first, we make the first of his class Dependency Injection as follows:
<?php
namespace Testmodule\DependencyInjection;
class TestDependencyContainer
{
private $validator;
public function __construct($validator)
{
$this->validator = $validator;
}
public function run($email)
{
$msg = " not valid ";
if ($this->validator->isValid($email)) {
$msg = " valid ";
}
return $msg;
}
}
Then we try to call on Controller:
<?php
namespace Testmodule\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class TestController extends Controller
{
/**
* @Route("/{email}", name="_test")
* @Template()
*/
public function indexAction($email)
{
$sc = new ContainerBuilder();
$sc->register('validatorEmail', 'Zend_Validate_EmailAddress');
$sc->register('test','Testmodule\DependencyInjection\TestDependencyContainer')
->addArgument(new Reference('validatorEmail'));
$emailisValid = $sc->get('test')->run(
$email
);
return array('emailcheckvalid' => "email $email is $emailisValid ");
}
}
Hmm, if successful, its staying in the view as shown below:
{% extends "Testmodule::layout.html.twig" %}
{% block content %}
Heiiii,... <strong><em><span style="color: red;"> {{emailcheckvalid}} </span> </em></strong>
{% endblock %}
Hm ... of course the principle of use at will (Use What you Need, Forget Everything Else) should still be used. The need for very complete component in Zend Framework can be used in Symfony with me registers the Zend Framework components in Symfony autoloader Framewok.
Zend Framework library that will we 'list'-right in Symfony2, we have saved in the folder \FrameworkSymfonyApp\vendor\namapackage as follows:
Well, after that, we document in its Symfony2 autoloader:
$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
...
));
$loader->registerPrefixes(array(
....
'Zend_' => __DIR__.'/../vendor/zf'
));
Ok, next is testing time. I will try to use his class Validator Zend Framework, first, we make the first of his class Dependency Injection as follows:
<?php
namespace Testmodule\DependencyInjection;
class TestDependencyContainer
{
private $validator;
public function __construct($validator)
{
$this->validator = $validator;
}
public function run($email)
{
$msg = " not valid ";
if ($this->validator->isValid($email)) {
$msg = " valid ";
}
return $msg;
}
}
Then we try to call on Controller:
<?php
namespace Testmodule\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class TestController extends Controller
{
/**
* @Route("/{email}", name="_test")
* @Template()
*/
public function indexAction($email)
{
$sc = new ContainerBuilder();
$sc->register('validatorEmail', 'Zend_Validate_EmailAddress');
$sc->register('test','Testmodule\DependencyInjection\TestDependencyContainer')
->addArgument(new Reference('validatorEmail'));
$emailisValid = $sc->get('test')->run(
);
return array('emailcheckvalid' => "email $email is $emailisValid ");
}
}
Hmm, if successful, its staying in the view as shown below:
{% extends "Testmodule::layout.html.twig" %}
{% block content %}
Heiiii,... <strong><em><span style="color: red;"> {{emailcheckvalid}} </span> </em></strong>
{% endblock %}
PHP CMS Frameworks
September 01, 2014
Read more →
No more posts to load.
About this blog
PHPCMSFramework.com
Tutorials for WordPress, Laravel, Drupal, Joomla, Symfony & more — including AI-powered PHP guides. Publishing since 2012.
Trending posts
- Building a RAG System in Laravel from Scratch
- Steps to create a Contact Form in Symfony With SwiftMailer
- Build a WhatsApp AI Assistant Using Laravel, Twilio and OpenAI
- CIBB - Basic Forum With Codeigniter and Twitter Bootstrap
- Laravel and Prism PHP: The Modern Way to Work with AI Models
- Build an AI Code Review Bot with Laravel — Real-World Use Case
- Drupal 7 - Create your custom Hello World module
- Symfony Framework - Introduction
- Create Front End Component in Joomla - Step by step procedure
- A step by step procedure to develop wordpress plugin
