article

Tuesday, February 5, 2019

How to create WordPress plugins with Shortcode Ajax

How to create WordPress plugins with Shortcode Ajax

1. Create folder name wp-content\plugins\"myplugins_shortcode_ajax"
2. Add index.php file wp-content\plugins\myplugins_shortcode_ajax\index.php
3. Add code index.php
//index.php
<?php
/**
* Plugin Name: Shortcode ajax
* Plugin URI: https://tutorial101.blogspot.com/
* Description: How to add a form to a shortcode in WordPress (using PHP and Ajax)
* Version: 1.0
* Author: Cairocoders
* Author URI: http://tutorial101.blogspot.com/
**/
$ajaxpostExample = new ajaxpostExample(); 
class ajaxpostExample {
 public function __construct() {
        $this->attach_actions();
  $this->attach_shortcodes();
    }
 function attach_actions() {
        add_action('wp_ajax_nopriv_ajax_do_something', array($this, 'do_something_serverside'));
        add_action('wp_ajax_ajax_do_something', array($this, 'do_something_serverside')); /* notice green_do_something appended to action name of wp_ajax_ */
        add_action('wp_enqueue_scripts', array($this, 'theme_enqueue_styles'), 99999);
    }
 function theme_enqueue_styles() {
        //include the js
  wp_enqueue_script('ajaxsample_script', plugin_dir_url(__FILE__) . 'js/ajax_call_to_handle_form_submit.js', array('jquery'));
  wp_enqueue_style('handlecss',  plugin_dir_url(__FILE__) . 'css/ajaxshortcodestyle.css');
  // in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
  // Register the script
  //wp_localize_script( $handle, $name, $data );
  wp_localize_script('ajaxsample_script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php'), 'we_value' => 1234));
 }
 function do_something_serverside() {
  global $wpdb;
  // output to ajax call   
  $txtname = $_POST['txtname'];
  $txtemail = $_POST['txtemail'];
  $txtsubject = $_POST['txtsubject'];
  $txtmessage = $_POST['txtmessage'];
  if ($txtname=='' OR $txtemail==''){
   echo "false"; 
  }else{ 
   echo "true";
  }
  //insert to a custom database table
  $wpdb->insert("test", array(
   "contactname" => $txtname
  ));
        die();
    }
 function attach_shortcodes() {
        add_shortcode('shortcode_ajax_form', array($this, 'shortcode_with_form_code')); //<p>[shortcode_ajax_form]</p>
    }
    function shortcode_with_form_code($atts, $content = null) {
        if ($this->formOk()) {
            return " <div>thanks your form has been submitted</div>";
        } else {
            return $this->show_form();
        }
    }
 function show_form() {
        $form = '<div class="well"><div id="display_rec"></div>
        <form id="green_form" action="">
          Name:<br>
          <input type="text" name="txtname" class="form-control" value="">
          <br>
          Email Address:<br>
          <input type="text" name="txtemail" class="form-control" value="">
    <br>
          Subject:<br>
          <input type="text" name="txtsubject" class="form-control" value="">
    <br>
          Message:<br>
          <textarea name="txtmessage" class="form-control" rows="5" cols="25" required="required" placeholder="Message"></textarea>
          <br>
          <br>
          <input type="submit" class="btn-primary" value="Submit" >
        </form></div>';
        return $form;
    }
 function formOk(){
        return false; 
    }
} 
4. Create folder name for js file wp-content\plugins\myplugins_shortcode_ajax\js\ajax_call_to_handle_form_submit.js then add this code
jQuery( document ).ready(function() {
    // Handler for .ready() called.
    //
    jQuery(function(){
  jQuery("#green_form").submit(function(event){
   event.preventDefault();
            var formOk = true;
            // do js validation 
   jQuery.ajax({
    url:ajax_object.ajax_url,
                type:'POST',
                data: jQuery(this).serialize() + "&action=ajax_do_something", //wp_ajax_nopriv_ajax_do_something, wp_ajax_ajax_do_something
    success:function(response){ 
     if(response=="true"){
                       //alert('success'); 
        jQuery("#display_rec").html("<div class='success'><p>Message Success Sent</p></div>")
                    }else{
                        jQuery("#display_rec").html("<div class='fail'>Please input required fields.</div>")
                        //alert('Please input required fields.'); 
                    } 
                }
   });
  }); 
    });
});
5. css code wp-content\plugins\myplugins_shortcode_ajax\css\ajaxshortcodestyle.css
.form-control {
    display: block;
    width: 100%;
    height: 34px;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.428571429;
    color: #555;
    background-color: #fff;
    background-image: none;
    border: 1px solid #ccc;
    border-radius: 4px;
    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}
.btn-primary {
    color: #fff;
    background-color: #428bca;
    border-color: #357ebd;
}
.well {
    padding: 19px;
    margin-bottom: 20px;
    background-color: #428bca;
    border: 1px solid #357ebd;color:#fff;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.05);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.05);
}
.success, .fail, .information, .attention {
 background-repeat: no-repeat;
 background-position: 10px center;
 height: 40px;
 font-size: 11px;
 line-height: 22px;
 margin-bottom: 20px;
 padding-top: 10px;
 padding-right: 10px;
 padding-bottom: 10px;
 padding-left: 50px;
 
}
/* Succes Notification Box */
.success     {
 background-color: #EBF8D6;
 border: 1px solid #A6DD88;
 color: #539B2D;
 background-image: url(../images/accept00.png);
}
/* Failure Notification Box */
.fail      {
 background-color: #FFECE6;
 border: 1px solid #FF936F;
 color: #842100;
 background-image: url(../images/delete00.png);
}
/* Information Notification Box */
.information    {
 background-color: #D3EEF1;
 border: 1px solid #81CDD8;
 color: #369CAB;
 background-image: url(../images/info0000.png);
}
/* Attention Notification Box */
.attention   {
 background-color: #FFFBCC;
 border: 1px solid #FFF35E;
 color: #C69E00;
 background-image: url(../images/warning0.png);
}
6. Shortcode [shortcode_ajax_form]

Related Post