How to use Ajax in WordPress

How to use AJAX in WordPress

I will the process about “How to use Ajax in WordPress” by using WordPress custom plugin, There is no much vary between themes and plugins to use Ajax in WP.

What is Ajax: 

Ajax (also AJAX an acronym for Asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not required (JSON is often used instead. See AJAJ), and the requests do not need to be asynchronous. These lines taken from “wikipedia” because I strongly believe wikipedia content about any topic.

Okay lets go in detail, In this example i am trying Search posts in WordPress by Ajax with jQuery UI auto-complete feature but its not working, Once its work i will update this article with latest one, For now i am provide basic example to understand the usage of Ajax in WordPress plugin with search posts feature.

Provide a HTML text box for search the post along with button field.

<label for="tags">Search Posts: </label>
 <input id="posttags" name="input_title" placeholder="post title..." nonce="<?php echo $nonce; ?>" />
 <input type="button" id="post_search" value="Search"/>

In the above code we note nonce HTML attribute, WP Ajax uses nonce for protect URL and recognize the request i.e its check is request come from with the site or different more about WordPress nonce Click here .

by using wp_create_nonce() we can create nonce for Ajax. In this example  I Was created  nonce with this string "ajax_posts_plugin". So the "$nonce" of the above HTML is, $nonce = wp_create_nonce("ajax_posts_plugin");

Create function for plugin initialization and Ajax calls explanation.

function plugin_get_post(){  
   $verifyNonce = $_POST['nonce'];  
   if ( !empty($verifyNonce) ){  
      if(!wp_verify_nonce( $verifyNonce, "ajax_posts_plugin")) {  
       echo "Sorry Your AJAX request not wroking"; }  
      }  
     global $wpdb;  
     $input_title = $_POST['input_title'];  
     if(!empty($input_title)){  
        $postid = $wpdb->get_var( "SELECT ID FROM ".$wpdb->prefix."posts W          HERE post_title = '" . $input_title . "'" );  
       $getpost= get_post($postid);  
  if(!empty($getpost)):  echo 'Post Title: '.$getpost->post_title.'<br>';   $user_info = get_userdata($getpost->post_author);  
  echo 'Author: '.$user_info->user_login.'<br>';  
  echo 'Date: '.$getpost->post_date.'<br>';  
  echo 'Post Content: '.$getpost->post_content;  die();  
  else:  echo 'Sorry no result found..!';  
  die();  endif;  
 }} 

//Plugin install action hook, WordPress fully loaded.
add_action( 'wp_loaded', 'plugin_get_post' );
//For logged-in users, But for both actions related to same 
 add_action("wp_ajax_plugin_get_post", "plugin_get_post");
//For logged-out users.
 add_action("wp_ajax_nopriv_plugin_get_post", "plugin_get_post");

“wp_ajax” and “wp_ajax_nopriv” actions are WordPress ajax actions for logged-in user and logged-out user respectively. but in this example assigned these actions to  same function,you can different functions.

In that function first verifying nonce if nonce is not verified by the “wp_verify_nonce()” it shows error message like “Sorry Your AJAX request not wroking”. So the verify condition likes

$verifyNonce = $_POST['nonce']; 
if ( !empty($verifyNonce) ){ 
 if(!wp_verify_nonce( $verifyNonce, "ajax_posts_plugin")) { 
echo "Sorry Your AJAX request not wroking"; } }

Next, $wpdb its database to access the DB with this global variable, If we receive as Ajax request value with this name “input_title” in POST method, We can proceed to next stage and run the select query then get values if such a post is exit or not in posts table at end of echo values we have to place die(); in conditional flow also, Other we will get zero(0) as Ajax response.

die(); 

Next, enqueues JS and CSS files in WordPress  with “plugin_js” function, as below.

//Plugin Script files are enqueued in this function.
function plugin_js(){
 wp_register_script( 'plugin-ajax', plugin_dir_url( __FILE__ ) . 'js/plugin_js.js', array( 'jquery','jquery-ui-core','jquery-ui-dialog'), '1.0', true );
 wp_localize_script( 'plugin-ajax', 'pluginAjaxExm', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
 //Enqeue JS
 wp_enqueue_script( array('plugin-ajax') );
 //Enqeue CSS
 wp_register_style( 'jqueryui', 'http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css' );
 wp_enqueue_style( 'jqueryui' );
 }

To enqueue JavaScript files or external JavaScript files in WordPress, We have register, localize and enqueue them in WordPress by using “wp_register_script”, “wp_localize_script” and “wp_enqueue_script”. Here I was register “plugin_js.js” file with jQuery dependency using “wp_register_script” then localize the JS file with “pluginAjaxExm” name along with “ajaxurl”. Ajax URL means every ajax handle by “admin-ajax.php” file which is located in “wp-admin” directory, then enqeue the JS file into local WordPress.

And we need to enqeue these all plugin JS and CSS files in “plugin_js” function with WordPress hooks as shown below

//Enqueue JavaScript files in WordPress.
 add_action( 'wp_enqueue_scripts', 'plugin_js' );

Plugin JS file, Which is handling plugin Ajax calls

jQuery.noConflict();
jQuery(document).ready( function($) {
 jQuery("#post_search").click( function(r) { 
 r.preventDefault(r); 
 var input_title = jQuery("#posttags").val();
 var nonce = jQuery(this).attr("nonce");
 //alert(input_title);
 jQuery('#response').html('<img src="wp-content/plugins/ajax-posts/js/ajax_load.GIF" alt="Loading..!" hieght="65" width="65" />');
 var data = {
 action: 'plugin_get_post',
 input_title: input_title,
 nonce: nonce
 };
 jQuery.post(pluginAjaxExm.ajax_url, data, function(response) {
 //alert('Got this from the server: ' + response);
 jQuery('#response').html(response);
 });
 });
});

WordPress Ajax call is almost like a nor Ajax call, There no much vary between them. In the above file

“jQuery.post(pluginAjaxExm.ajax_url, data, function(response) { // Code goes here…

}”

here “pluginAjaxExm.ajax_url” means what we localize the Plugin JS file with “pluginAjaxExm” and Ajax URL to “admin-ajax.php”. Data variable indicates,Ajax action, request string and nonce for verifying. so that’s why I mentioned  action to “plugin_get_post” WordPress Ajax will check this exit or not if its exited its send the request data and revives data from server to the client.

To test the plugin create new page with below short code in page text area.

[ajax_onscreen]

I added some additional code for better understanding, Don’t bother about its in simple procedure.

That’s it Okay , I understand first time its little confusing. You can download the original file observe the comments for better understanding.

Download plugin Click here

 

You can comment any questions about this, Thank you.

 

 

Advertisements

Remove index.php in CodeIgniter url and default controller

Remove index.php in CodeIgniter url and default controller:

Few people are asked me how to “Remove index.php in CodeIgniter url and default controller in CodeIgniter”.

CodeIgniter   EllisLab

CodeIgniter(CI) is good application to build web portals using PHP MVC frame works and learning PHP MVC also for beginners, Okay Lets move our topic to “Remove index.php in CodeIgniter(CI) url and default controller”.

Follow the steps for removes “index.php” in URL

Step 1: Download the CI from CI official web site, Click here for CI download

Step 2: If you want rename your download CI yes you can as you want or leave as it is.Then place the application folder into your local server root. Suppose if your using           WAMP Server the root will be Local drive:\\wamp\www\your CI application.Suppose if your using XAMPP the root will be Local drive:\\xampp\\htdocs\your CI application.

Step 3: Now you have to enable “rewrite_module” in our local servers for WAMP, Click on    quick lunch icon of WAMP >> Apache >> Apache modules >> rewrite_module, enable the “rewrite_module” and restart WAMP Server. For XAMPP, XAMPP >> apache >> conf >> open httpd.conf file and find “LoadModule rewrite_module modules/mod_rewrite.so” make sure this line comment or not if yes just remove “#” at starting of the line and restart XAMPP.

Step 4: Go to your server root directory and open “CodeIgniter application” folder then find “application” folder and open it and find “config” folder and open it then find “config.php” file and open using PHP program file editor. for example I was renamed the CI application file like “codeigniter213” so my codeigniter application flow like as below “codeigniter >> application >> config >> config.php”.

Step 5: Find these variables in “config.php” and change like as shown below.                      $config[‘base_url’] = ”;  and replace with your site URL like this “$config[‘base_url’] = ‘ http://localhost:85/CodeIgniter213/ ‘; ” and ” $config[‘index_page’] = ‘index.php’; ” make this variable as empty like ” $config[‘index_page’] = ”; ” Note: Here “CodeIgniter213” is consider for example purpose only you have to change as you need.

Step 6: Create a file name ” .htaccess ” and place this file into CodeIgniter application folder, For example “codeigniter213 >> .htaccess “, Open file any text editor copy and paste the flowing code in ” .htaccess

<IfModule mod_rewrite.c> 
 RewriteEngine On
 #rename "codeIgniter213" with your application directory 
 #For example you rename the entire CodeIgniter application as "mysite" 
 #then, the "RewriteBase /" will be like this "RewriteBase /mysite" 
 #same as at line number 10, "RewriteRule ^(.*)$ /codeIgniter213/index.php #/$1 [L]" will be like this "RewriteRule ^(.*)$ /mysite/index.php/$1 [L]"
 RewriteBase /codeIgniter213
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ /codeIgniter213/index.php/$1 [L]
</IfModule>

If your confuses with above code you can download ” .htaccess ” file, Click here. Note : you have to replace “codeigniter213” with CI application name. That’s it your done.

Follow the steps to change default controller of your CI application

What is default controller ? Ans: When we try to enter our CodeIgniter application URL in bower at that time CodeIgniter check which controller it has to call as configure in “routes.php” file with “default_controller“.

Open “routes.php” file which is located in “config folder of application folder” in CodeIgniter application for example “codeigniter213 >> application >> config >> routes.php “. Find the ” $route[‘default_controller’] = “welcome”; ” here welcome is default controller for CodeIgniter to default you have to create a new controller based on CodeIgniter controller creation rules for more how to controllers in CodeIgniter Click here .

Suppose we create a new controller called “test” and i want make this as my default controller, Just i need to change  ” $route[‘default_controller’] = “welcome”; ” this veriable as ” $route[‘default_controller’] = “test“; ” in “routes.php” file.

Please don't hesitate to contact me on this.
You can comment your opinion ,Thank you, 
Achyuth 401