Ajax in Wordpress to reload a SELECT every second - php

My target is to take a page of an existent WP theme and customize a full width page, to make that every 1 seconds a MySQL SELECT query is reloaded and the results are shown.
Starting with this snippets I have made the following editing/new files:
template-fullwidth.php
functions.php
my.js (new file)
GetPostDate.php (new file)
What I have done
I started from the template-fullwidth.php of a theme and add the following code between the DIV of the post. The place where I wanted to show the results is between <div id="MaxPostDate"> tags.
</div><!-- .post -->
<!-- START CUSTOM PAGE CODE -->
<?php
if ( is_user_logged_in() ) {
// --- START IF USER LOGGED IN --- //
// Get the current user name and id
?>
<div id="MaxPostDate"></div>
<?php
// --- END IF USER LOGGED IN --- //
} else {
// --- START IF USER NOT LOGGED IN --- //
echo "<p>You have to log-in to see this content</p>";
// --- END IF USER NOT LOGGED IN --- //
}
?>
<div class="result"></div>
<!-- END CUSTOM PAGE CODE -->
<?php comments_template( '', true ); ?>
</div><!-- .posts -->
then I have edited the functions.php file of the theme adding this in the end:
function add_myjavascript(){
wp_enqueue_script( 'ajax-implementation.js', get_bloginfo('template_directory') . "/js/my.js", array( 'jquery' ) );
}
add_action( 'init', 'add_myjavascript' );
function MyAjaxFunction(){
//get the data from ajax() call
$TableContent = $wpdb->get_results("
SELECT MAX(`post_date`) AS MaxDate FROM wp_posts"
);
foreach($TableContent as $Content){echo "<h1>" . $Content->MaxDate . "</h1>";}
// Return the String
die($results);
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_MyAjaxFunction', 'MyAjaxFunction' );
add_action( 'wp_ajax_MyAjaxFunction', 'MyAjaxFunction' );
?>
Then, I have made this my.js in the js folder of the theme:
jQuery(document).ready(function refresh_div() {
jQuery.ajax({
url:'/MySite/wp-content/themes/hemingway/GetPostDate.php',
type:'POST',
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000););
And finally make another file GetPostDate.php
<?php
$TableContent = $wpdb->get_results("
SELECT MAX(`post_date`) AS MaxDate FROM wp_posts"
);
foreach($TableContent as $Content){echo "<h1>" . $Content->MaxDate . "</h1>";
?>
The problems
nothing appear inside the DIV id="MaxPostDate"
I have wrote two time the same query (SELECT MAX(post_date) AS MaxDate FROM wp_posts), I would be wrote just one time!

I think the problem is with your AJAX URL.
Execute your AJAX in footer.php like below:
jQuery.ajax({
url:'<?php echo admin_url('admin-ajax.php'); ?>',
type:'POST',
success:function(results) {
jQuery(".result").html(results);
}
});
then you don't need GetPostDate.php file either.

this my.js in the js folder of the theme
jQuery(document).ready(function refresh_div() {
jQuery.ajax({
url:'//MySite/mysite/wp-admin/admin-ajax.php',
action:'MyAjaxFunction',
type:'POST',
dataType:json,
success:function(results) {
jQuery(".result").html(results.result);
}
});
}
t = setInterval(refresh_div,1000););
the functions.php file of the theme adding this in the end:
function MyAjaxFunction(){
//get the data from ajax() call
$jsonresult = array();
$TableContent = $wpdb->get_results("
SELECT MAX(`post_date`) AS MaxDate FROM wp_posts"
);
foreach($TableContent as $Content){
$jsonresult['result'] = $Content->MaxDate
}
echo json_encode($jsonresult);
die();
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_MyAjaxFunction', 'MyAjaxFunction' );
add_action( 'wp_ajax_MyAjaxFunction', 'MyAjaxFunction' );

Related

WP functions undefined in plugin

I am having trouble with a plugin I am writing, the plugin shows a form and the form submits to ajaxupload.php.
Basically in my plugin file:
add_action('plugins_loaded','add_to_menu');
function add_to_menu(){
add_action('admin_menu', 'test_plugin_setup_menu');
}
function test_plugin_setup_menu(){
add_menu_page( 'Test Plugin Page', 'add new entry', 'manage_options', 'test-plugin-link', 'test_init' );
// ,'dashicons-database-add'
}
function test_init(){
//echo "<h1>Hello World!</h1>";
// do_action( 'admin_init' );
include(ABSPATH."/wp-content/plugins/my-plugin/form.php");
}
In form.php I can call wp functions!
<?php
// this works!
echo wp_get_current_user()->user_login;
?>
<form>
...
</form>
<script>
$(document).ready(function(){
$("#my_form").on("submit",function(e){
e.preventDefault();
var sendData = $( this ).serialize();
$.ajax({
url: "../wp-content/plugins/my-plugin/ajaxupload.php",
type: "POST",
data: new FormData(this),
...
</script>
in Ajaxupload.php I can't use any WP constants or functions before submission...
if( !empty($_POST['imgurl']) || !empty($_FILES['image']) )
{
$someform_field = $_POST["name"];
echo wp_get_current_user()->user_login; //this line fails
//then call to wpdb to add data to DB
What should be the correct sequence to make wp functions usable in the ajaxupload.php file?
You have to load the wp-load.php file in your ajaxload.php, which loads all wordpress functions, because your ajaxload.php file is called directly:
<?php
require_once __DIR__ . '/../../../wp-load.php';
$someform_field = $_POST["name"];
$user = wp_get_current_user()->user_login; // should now work
//then call to wpdb to add data to DB

Using wordpress action to modify div content

I'm trying to modify a div's content everytime when something is added to the woocommerce shopping cart. For this example the content is gonna be the current total cart value.
So first I created a simple plugin called "test-cart-value" which contains the following code:
<?php
function test_cart_value() {
echo "<div>" . WC()->cart->total . "</div>";
}
add_shortcode('test_cart_value_shortcode', 'test_cart_value');
This works fine, wherever I place the shortcode I get the current cart value after page load.
So, now I want this printed value to updated every time something is added to the cart, without reloading the page. The idea was to use the action hook woocommerce_cart_updated and call the function - so everytime something in the cart changes, the new cart value gets echoed:
function action_woocommerce_cart_updated() {
test_cart_value();
};
// add the action
add_action( 'woocommerce_cart_updated', 'action_woocommerce_cart_updated', 10, 0 );
The problem is, now I'm not able to dynamically add products to the shopping cart. Whenever I hit the "add to cart" button, the loading animation loads forever.
How to do this properly?
I was trying different approaches with Ajax and different Hooks, but so far nothing worked.
Any Ideas? Thanks in advance!
Edit:
So I tried this as my plugin code
function test_cart_value() {
echo "<div id='cart_test'>" . WC()->cart->total . "</div>";
}
add_shortcode('test_cart_value_shortcode', 'test_cart_value');
// define the actions for the two hooks created, first for logged in users and the next for logged out users
add_action("woocommerce_cart_updated", "cart_update");
// define the function to be fired for logged in users
function cart_update() {
$cart = WC()->cart->total;
$result['type'] = "success";
$result['new_cart'] = $cart;
$result = json_encode($result);
//if I uncomment the "die" function, the page won't load
// die();
}
// Fires after WordPress has finished loading, but before any headers are sent.
add_action( 'init', 'script_enqueuer' );
function script_enqueuer() {
// Register the JS file with a unique handle, file location, and an array of dependencies
wp_register_script( "test_script", plugin_dir_url(__FILE__).'test_script.js', array('jquery') );
// localize the script to your domain name, so that you can reference the url to admin-ajax.php file easily
wp_localize_script( 'test_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
// enqueue jQuery library and the script you registered above
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'test_script' );
}
And my test_script.js code:
jQuery(document).ready( function() {
jQuery(".ajax_add_to_cart").click( function(e) {
e.preventDefault();
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "cart_update"},
success: function(response) {
if(response.type == "success") {
jQuery("#cart_test").html(response.new_cart);
}
else {
alert("Your like could not be added");
}
}
});
});
});
So I thought that the cart_update() function should fire when I press the "ajax_add_to_cart" Button, but I get an error 400.
Any ideas?
Thanks!
made it work with woocommerce_add_to_cart_fragments.

Exclude a dynamic value from cache with Wordpress Super Cache

I'm using the Super Cache plugin.
For some time I was looking for a solution, but without success. I need to disable the cache for one function in the file functions.php.
add_shortcode('custom_counter', 'example_shortcode');
function example_shortcode() {
// Get custom counter option value
$counter = get_option( 'wc-custom-counter' );
return '<span class="custom-counter">' . $counter . ' rub.</span>';
}
This is shortcode is used on the created custom page. It is necessary that the data output by this shortcode does not fall into the page cache.
Adapted from this old WSE thread, you will find below the complete way to make it working.
Here we display a spinner loading icon that will be replaced by the counter real non cached value through ajax. Javascript stays always active even in a cached page, so it can change anything needed on the page via Ajax or via any detected event. So there is no need to exclude anything in the plugin settings.
The replacement code:
// The shortcode
add_shortcode('custom_counter', 'customer_counter_shortcode');
function customer_counter_shortcode() {
// Start buffering
ob_start();
// Using woocommerce existing animated spinner gif icon
$loading_url = home_url( '/wp-content/plugins/woocommerce/assets/images/select2-spinner.gif' );
// Displaying a "Loading spinner icon + text to be replaced by Ajax value
echo '<span class="custom-counter">
<img id="loading-img" src="'.$loading_url.'" alt="Loading..." style="opacity:0.5; display:inline-block; vertical-align: middle;" />
<span style="opacity:0.5;"> ' . _("loading…") . '</span>
</span>';
?>
<script type="text/javascript">
jQuery( function($){
if (typeof woocommerce_params === 'undefined')
return false;
$.ajax({
type: 'POST',
url: woocommerce_params.ajax_url,
data: {
'action': 'custom_counter',
'custom-counter': true,
},
success: function (result) {
$('.custom-counter').text(result);
console.log('response: '+result); // just for testing | TO BE REMOVED
},
error: function(error){
console.log(error); // just for testing | TO BE REMOVED
}
});
});
</script>
<?php
return ob_get_clean(); // Return the buffered code
}
// The wordpress ajax hooked function (for logged in and non logged users)
add_action('wp_ajax_custom_counter', 'ajax_custom_counter');
add_action('wp_ajax_nopriv_custom_counter', 'ajax_custom_counter');
function ajax_custom_counter() {
if( isset($_POST['custom-counter']) && $_POST['custom-counter'] )
echo get_option( 'wc-custom-counter' ); // Get option value
exit();
}
Code goes in function.php file of your active child theme (or active theme). tested and works.
You cannot exclude a function from cache plugins. Instead you can exclude an URL (in WP Super Cache, go to 'Settings > WP Super Cache > Advanced' - 'Accepted Filenames & Rejected URIs' section).
So, call this function using AJAX instead calling directly and you can exclude the AJAX URL.
Here is the full code.
Add these in theme's functions.php:
add_action('wp_ajax_customer_counter', 'customer_counter_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_customer_counter', 'customer_counter_ajax_handler'); // wp_ajax_nopriv_{action}
function customer_counter_ajax_handler() {
// Get custom counter option value
$counter = get_option( 'wc-custom-counter' );
echo $counter . ' rub.';
}
Replace all your shortcodes [custom_counter] instances with <span class="customer_counter_shortcode"> </span>.
Add this script to theme's footer.php:
jQuery(function($){
$.ajax({
url : '<?php echo site_url(); ?>/wp-admin/admin-ajax.php', // AJAX handler
data : { action : 'customer_counter' },
type : 'POST',
success : function( $result ){
if( $result ) {
$('.customer_counter_shortcode').html($result);
}
}
});
});
You can then exclude the AJAX URL - /wp-admin/admin-ajax.php?action=customer_counter.

How to change category of post in WP_Query

How can I pass a category name to new WP_Query when I click specific button with category name?
I've got this in my functions.php
<?php
add_action('wp_ajax_my_action', 'data_fetch');
add_action('wp_ajax_nopriv_my_action', 'data_fetch');
function data_fetch(){
$the_query = new WP_Query(array('post_type'=>'wydarzenie','posts_per_page'=>2, 'category_name'=>'2017'));
if($the_query->have_posts()):
while($the_query->have_posts()): $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<p><?php the_content(); ?></p>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
?>
and this on page with my default loop posts
function fetch(){
$.post('/PRACA/FundacjaWP/wp-admin/admin-ajax.php', {'action':'my_action'}, function(response){
$("#pick-event").html(response);
});
}
$(".show-specific-events").on("click", function(e){
e.preventDefault();
var category = $(this).text();
fetch();
});
I want load a new query with new loop based on category choose when I click a button. Now I set category '2017' but I want it to be dynamic.
Here we will learn how to use AJAX in WordPress. We will see how WordPress AJAX works as Beginner level. In this, we will pass a variable from JavaScript and pass it to WordPress theme function file. After doing the necessary process, we will pass the resulting content back to the JavaScript.
We are assuming that you already know how to enqueue JavaScript, etc.
JavaScript:
jQuery(document).ready(function($) {
$(".show-specific-events").on("click", function(e){
e.preventDefault();
var category = $(this).text();
// This does the ajax request
$.ajax({
url: codecanal_ajax_object.ajax_url,
data: {
'action':'codecanal_ajax_request',
'category_name' : category
},
success:function(data) {
// The OutPut after successfull receiveing content
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
});
Implementation of Argument
If you are using in theme custom coding then put the below code in theme’s functions.php file
function codecanal_ajax_request() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
// You can check what data is received in the function by debugging it
// print_r($_REQUEST);
$category_name = $_REQUEST['category_name'];
$the_query = new WP_Query(array('post_type'=>'wydarzenie','posts_per_page'=>2, 'category_name'=> $category_name));
if($the_query->have_posts()):
while($the_query->have_posts()): $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<p><?php the_content(); ?></p>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
// To return to the front page, always finish after echoing the desired content.
die();
}
add_action( 'wp_ajax_codecanal_ajax_request', 'codecanal_ajax_request' );
// For allowing non-logged in users to use AJAX function
// add_action( 'wp_ajax_nopriv_codecanal_ajax_request', 'codecanal_ajax_request' );
/* We can define the AJAX url with using wp_localize_script */
function codecanal_ajax_enqueue() {
wp_localize_script( 'ajax-script', 'codecanal_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'codecanal_ajax_enqueue' );
Your code should look like this.
$args=array(
'posts_per_page' => 50,
'post_type' => 'my_custom_type'
'cat' => $cat_id,
);
$wp_query = new WP_Query( $args );
and when you use jquery at that time you need to pass category id on that.

How to get wp_ajax to work with jQuery $.post

Straight from WP Codex: http://codex.wordpress.org/AJAX_in_Plugins
I have this in my functions.php:
add_action( 'admin_footer', 'my_action_javascript' );
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
<?php
}
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
And I don't get a response. I do get an alert saying 'Got this from the server: ', but no response. What gives?
Running your code on two separate wordpress installs from within a plugin file (plugin-name.php) and from within functions.php in my theme, it returns the proper value both times. There do not seem to be any errors in your code either.
Is this the only javascript you're including in the admin area?

Categories