/**
Plugin Name: ajax test
Plugin URI: https://templateeye.com/plugins/ajax/
Description: Ajax Test shortcode [aj_exam].
Author: Tamal Sarker
Version: 1.0.0
Author URI: http://templateeye.com/
*/
/* Set constant path to the plugin directory. */
define('EYE_PATH', plugin_dir_path(__FILE__));
/* Set the constant path to the plugin directory URI. */
define('EYE_URL', plugin_dir_url(__FILE__));
/* Add CSS */
function eye_styles(){
wp_register_style( 'header_cart_css', EYE_URL . 'assets/css/header-cart.css' , array(), '1.1.0', false );
wp_enqueue_style( 'header_cart_css' );
}
add_action('wp_head', 'eye_styles', 5);
/* Add JS */
function eye_scripts() {
wp_register_script( 'header_cart_js', EYE_URL . 'assets/js/header-cart.js', array('jquery'), '1.0.0', true );
wp_enqueue_script( 'header_cart_js' );
wp_localize_script('header_cart_js', 'ajax_custom', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax-nonce'),
'getID' => get_the_ID()
));
}
add_action('wp_footer', 'eye_scripts', 5);
//call post function
require_once(EYE_PATH . 'function.php');
add_shortcode('aj_exam', 'aj_exam');
function aj_exam(){
$out = '<div id="show-enquiry"></div>'; // Click Output
$out .= '<button id="add-enquiry">Add Enquiry</button>'; // Click Input
return $out;
}
function.php
function enquiry_ajax_request() {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 5,
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<h3><?php the_title(); ?></h3>
<p><?php the_content(); ?></p>
<?php the_post_thumbnail(); ?>
<?php endwhile;
wp_die();
}
add_action( 'wp_ajax_enquiry_ajax_request', 'enquiry_ajax_request' );
add_action( 'wp_ajax_nopriv_enquiry_ajax_request', 'enquiry_ajax_request' );
header-cart.js
jQuery(document).ready(function($) {
jQuery( "#add-enquiry" ).on('click',function() {
$.ajax({
url: ajax_custom.ajaxurl,
data: {
'action':'enquiry_ajax_request'
//'post_id' : header_cart_js.getID
},
success:function(data) {
//alert('okay');
//console.log(data);
$('#show-enquiry').html(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
});
TemplateEYE says:
TemplateEYE
admin says:
Good job