Jquery .click function for getting subcat of id element - javascript

I try to build a car search plugin, with 3 category levels.
Like: 1 row = Maincat, 2 row = Subcat, 3 row = Subsubcat...
Here is an example of what i want to do:
https://www.aez-wheels.com/3DKonfigurator/index.php?lcs=onz2sm13at&lng=en
in my code the first level appears and the second level loads. but the third level is not loading.
I Think the problem is, that the second row is created dynamicaly.
Can somebody tell me where i have a wrong code?
// Loading WordPress hooks
function __construct()
{
add_action( 'avada_after_header_wrapper', array($this, 'llm_car_conf_list') );
// Register ajax action
add_action( 'wp_ajax_get_cat', array($this, 'getCat') );
// Register ajax action for non loged in user
add_action('wp_ajax_nopriv_get_cat', array($this, 'getCat') );
}
// function for the maincat
function llm_car_conf_list() {
if ( is_front_page() ) {?>
<div class="llm_car_container">
<div class="car_wrapper">
<div class="car_row">
<div class="car_title"><h2>1. Fahrzeug wählen</h2></div>
<ul id="maincat" class="car_conf"><?php
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'parent' => 0
));
foreach ( $categories as $category ) {
printf( '<li class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
}
?></ul></div>
// Jquery to load first subcat
<script type="text/javascript">
(function($){
$("#maincat li").click(function(){
$("#second_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#second_row").append(data);
}
});
});
})(jQuery);
</script>
<div class="car_row">
<div class="car_title"><h2>2. Typ wählen</h2></div>
<ul id="second_row" class="car_conf"></ul>
</div>
// Jquery to load subsubcat
<script type="text/javascript">
(function($){
$("#second_row li").click(function(){
$("#third_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#third_row").append(data);
}
});
});
})(jQuery);
</script>
<div class="car_row">
<div class="car_title"><h2>3. Jahrgang wählen</h2></div>
<ul id="third_row" class="car_conf"></ul>
</div>
</div>
</div>
<?php
}
}
// Function to load the subcats
function getCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
}
die();
}

Here is my full code, that works in my plugin
<?php
defined('ABSPATH') or die("Thanks for visting");
if ( ! class_exists( 'frontendAjaxDdown' ) ):
class frontendAjaxDdown
{
// Loading WordPress hooks
function __construct()
{
add_action( 'avada_after_header_wrapper', array($this, 'llm_car_conf_list') );
// Register ajax action
add_action( 'wp_ajax_get_cat', array($this, 'getCat') );
add_action( 'wp_ajax_get_subcat', array($this, 'getSubCat') );
add_action( 'wp_ajax_get_subsubcat', array($this, 'getSubSubCat') );
// Register ajax action for non loged in user
add_action('wp_ajax_nopriv_get_cat', array($this, 'getCat') );
add_action('wp_ajax_nopriv_get_subcat', array($this, 'getSubCat') );
add_action('wp_ajax_nopriv_get_subsubcat', array($this, 'getSubSubCat') );
}
function llm_car_conf_list() {
if ( is_front_page() ) {?>
<div class="llm_car_container">
<div class="car_wrapper">
<div class="car_row">
<div class="car_title"><h2>1. Fahrzeug wählen</h2></div>
<ul id="maincat" class="car_conf"><?php
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'parent' => 0
));
foreach ( $categories as $category ) {
printf( '<li class="car_list_item"><a id="%1$s"><img src="http://climair-schweiz.ch.185-117-169-242.srv201.webpreview.ch/wp-content/uploads/carbrands/%2$s.png" width="20px">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
} ?>
</ul>
</div>
<script type="text/javascript">
(function($){
$("#maincat li").click(function(){
$("#second_row, #third_row, #fourth_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#second_row").append(data);
}
});
});
})(jQuery);
</script>
<div class="car_row">
<div class="car_title"><h2>2. Model wählen</h2></div>
<ul id="second_row" class="car_conf"></ul>
</div>
<div class="car_row">
<div class="car_title"><h2>3. Baujahr | Typ wählen</h2></div>
<ul id="third_row" class="car_conf"></ul>
</div>
<div class="car_row">
<div class="car_title"><h2>4. Form | Türen wählen</h2></div>
<ul id="fourth_row" class="car_conf"></ul>
</div>
</div>
</div> <?php
}
}
function getCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
} ?>
<script type="text/javascript">
(function($){
$("#second_row li").click(function(){
$("#third_row, #fourth_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_subcat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#third_row").append(data);
}
});
});
})(jQuery);
</script> <?php
die();
}
function getSubCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
}
?> <script type="text/javascript">
(function($){
$("#third_row li").click(function(){
$("#fourth_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_subsubcat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#fourth_row").append(data);
}
});
});
})(jQuery);
</script> <?php
die();
}
function getSubSubCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li class="car_list_item">%2$s</li>',
esc_url( get_category_link( $category->term_id ) ),
esc_html( $category->cat_name )
);
}
die();
}
}
endif;
new frontendAjaxDdown();
?>

Related

WooCommerce set cart quantity with AJAX?

I've now been scratching my head about this for several days and need some pointers.
I'm making a custom theme totally from scratch for a WooCommerce site and now I'm trying to get the cart functionality to work. I'm stuck at trying to have buttons (+/-) for updating the quantity of a product item in the cart.
The problem to me seems to be that the WC() I use inside functions.php is not the same instance as the current frontend-session, or something among those lines. At least my thought for now.
If I've debugged correctly the WC()->cart->set_quantity($cart_item_key, 0) gives no error (if using number 0), all other numbers gives '500 (Internal Server Error)'. But even with 0 quantity in cart is never changed nonetheless.
I've enqueued the scripts correctly so the AJAX function call executes fine when the button is clicked.
Here's my HTML and PHP (simplified)
<div class="cart-items">
<?php foreach(WC()->cart->get_cart() as $cart_item_key => $cart_item) : ?>
<div class="cart-item">
<div class="quantity" id="cart-qty-<?php echo $cart_item_key ?>">
<button class="minus" id="cart-subtract"
onclick="updateCartQuantity('<?php echo $cart_item_key ?>', '<?php echo $cart_item['quantity'] ?>', -1)">-</button>
<p><?php echo $cart_item['quantity'] ?></p>
<button class="plus" id="cart-add">+</button>
</div>
</div>
<? endforeach; ?>
</div>
Here's my JS (inside a file called shopping-ajax.js)
function updateCartQuantity(cart_item_key, current_qty, value) {
function qty_cart() {
jQuery.ajax({
type: "POST",
url: my_ajax_object.ajax_url,
data: {
action: "update_cart",
hash: cart_item_key,
quantity: current_qty,
value: value,
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
},
});
}
qty_cart();
}
Here's my PHP function (inside functions.php)
function updateCartQuantity(){
$cart_item_key = $_REQUEST['cart_item_key'];
$quantity = $_REQUEST['quantity'];
$value = $_REQUEST['value'];
WC()->cart->set_quantity($cart_item_key, $quantity + $value);
echo $quantity + $value;
wp_die();
}
add_action( 'wp_ajax_nopriv_update_cart', 'updateCartQuantity' );
add_action( 'wp_ajax_update_cart', 'updateCartQuantity' );
A massive thanks for any help or pointer in advance!
You should manage product qty according to the qty input box(change qty).
My JS:
location: theme directory -> js -> custom.js
jQuery( function( $ ) {
$( document ).on( 'change', 'input.qty', function() {
var $thisbutton = $(this);
var item_hash = $( this ).attr( 'name' ).replace(/cart\[([\w]+)\]\[qty\]/g, "$1");
var item_quantity = $( this ).val();
var currentVal = parseFloat(item_quantity);
$.ajax({
type: 'POST',
url: cart_qty_ajax.ajax_url,
data: {
action: 'my_cart_qty',
hash: item_hash,
quantity: currentVal
},
success: function(response) {
jQuery(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]);
//jQuery(document.body).trigger('update_checkout');
}
});
});
});
fuctions.php -
Setup Enqueue Ajax Scripts:
function enqueue_cart_qty_ajax() {
wp_register_script( 'my_cart_qty-ajax-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '', true );
wp_localize_script( 'my_cart_qty-ajax-js', 'cart_qty_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'my_cart_qty-ajax-js' );
}
add_action('wp_enqueue_scripts', 'enqueue_cart_qty_ajax');
Ajax call -
function ajax_my_cart_qty() {
// Set item key as the hash found in input.qty's name
$cart_item_key = $_POST['hash'];
// Get the array of values owned by the product we're updating
$threeball_product_values = WC()->cart->get_cart_item( $cart_item_key );
// Get the quantity of the item in the cart
$threeball_product_quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9\.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)) ), $cart_item_key );
// Update cart validation
$passed_validation = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $threeball_product_values, $threeball_product_quantity );
// Update the quantity of the item in the cart
if ( $passed_validation ) {
WC()->cart->set_quantity( $cart_item_key, $threeball_product_quantity, true );
}
// Refresh the page
echo do_shortcode( '[woocommerce_cart]' );
die();
}
add_action('wp_ajax_my_cart_qty', 'ajax_my_cart_qty');
add_action('wp_ajax_nopriv_my_cart_qty', 'ajax_my_cart_qty');

Live WooCommerce Product Search Form using AJAX (Shortcode)

While the search form works, I need help fixing the problem that occurs when the form is empty after having been typed into.
What I mean is this:
If you start typing a search query, you start to get results. This part works fine.
But if you, while / after typing, remove the text from the search form - you get a list of ALL products.
It should only show results if and when typing and show nothing if and when empty.
Fix:
After applying a modified version of the solution offered and provided by Terminator-Barbapapa as per below, it works as intended.
The code below might not be 100% correct, but it works.
The code so far:
add_shortcode('live_search', 'live_search_function');
function live_search_function() { ?>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>
<div id="productfetch"></div>
<?php
}
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() { ?>
<script type="text/javascript">
function fetch() {
if( document.getElementById('keyword').value.trim().length == 0 ) {
jQuery('#productfetch').html('');
} else {
jQuery.ajax( {
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#productfetch').html( data );
}
});
}
}
</script>
<?php
}
add_action('wp_ajax_data_fetch' , 'product_fetch');
add_action('wp_ajax_nopriv_data_fetch','product_fetch');
function product_fetch() {
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'product' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><?php the_title();?></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
You can add a check in your fetch() function to see if your input field is empty. If so, clear the datafetch div, else run your AJAX.
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() { ?>
<script type="text/javascript">
function fetch() {
if( document.getElementById('keyword').value.trim().length == 0 ) {
jQuery('#productfetch').html('');
} else {
jQuery.ajax( {
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#productfetch').html( data );
}
});
}
}
</script>
<?php
}

How to load more logo's with ajax?

I found a solution how to get a load more button that displays more content on click, but it was for posts, I want to make it work for my custom post type 'Klanten'.
I tried editing the code to match my post type, but I get an error: "Undefined index: offset"
functions.php
wp_enqueue_script( 'dfib-theme-custom', get_template_directory_uri() .'/js/custom.js', array('jquery') );
wp_localize_script( 'dfib-theme-custom', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
add_action( 'wp_ajax_load_more_posts', 'load_more_posts' );
add_action( 'wp_ajax_nopriv_load_more_posts', 'load_more_posts' );
function load_more_posts(){
global $post;
$args = array('post_type'=>'klanten', 'posts_per_page'=> 4, 'offset'=> $_POST['offset']);
$rst=[];
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()):$query->the_post();
$rst[] = $post;
endwhile;
wp_reset_postdata();
$offset = $_POST['offset']+4;
endif;
wp_send_json_success(array('klanten'=>$rst, 'offset'=>$offset));
}
custom.js
$('#load_more_posts').on('click', function(e){
console.log('hi');
e.preventDefault();
var $offset = $(this).data('offset');
console.log('var'+$offset);
$.ajax({
method: 'POST',
url: ajax_object.ajax_url,
type: 'JSON',
data: {
offset: $offset,
action: 'load_more_posts'
},
success:function(response){
console.log(response);
$('#load_more_posts').data('offset', parseInt(response.data.offset));
}
});
})
php-file
$query = new WP_Query( array(
'post_type' => 'klanten',
'posts_per_page' => 4,
'offset' => 0,
'paged' => 1,
'order' => 'ASC',
'orderby' => 'rand',
) );
if ( $query->have_posts() ) { ?>
<div class="klanten__wrapper">
<?php
while ( $query->have_posts() ) :
$query->the_post();
?>
<div class="logo__wrapper">
<img class="klant__logo" src="<?php the_post_thumbnail_url(); ?>">
</div>
<?php endwhile; ?>
<div id="load_more_posts" class="loadmore">Load More...</div>
</div>
<?php
wp_reset_postdata();
return ob_get_clean();
}
Console log
I want to show 4 logo's (elements), and load 4 more each time someone clicks the loadmore button
Replace this
<div id="load_more_posts" class="loadmore" data-offset="4">Load More...</div>
You need to return ajax data with logo array and then append data like below code.
AJAX call
$('#load_more_posts').on('click', function(e){
console.log('hi');
e.preventDefault();
var $offset = $(this).data('offset');
console.log('var'+$offset);
$.ajax({
method: 'POST',
url: ajax_object.ajax_url,
type: 'JSON',
data: {
offset: $offset,
action: 'load_more_posts'
},
success:function(response){
console.log(response);
var html = "";
$(response.data.klanten).each(function(index,value) {
html += '<div class="logo__wrapper"> <img class="klant__logo" src="'+value.post_thumbnail+'"></div>'
});
$('.logo_wrapper').append(html);
$('#load_more_posts').data('offset',
parseInt(response.data.offset));
}
});
})
HTML Code
<div class="klanten__wrapper">
<div class="logo_wrapper">
<?php
while ( $query->have_posts() ) :
$query->the_post();
?>
<div class="logo__wrapper">
<img class="klant__logo" src="<?php the_post_thumbnail_url(); ?>">
</div>
<?php endwhile; ?>
<div>
<div id="load_more_posts" class="loadmore">Load More...</div>
</div>
function.php
wp_enqueue_script( 'dfib-theme-custom', get_template_directory_uri() .'/js/custom.js', array('jquery') );
wp_localize_script( 'dfib-theme-custom', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
add_action( 'wp_ajax_load_more_posts', 'load_more_posts' );
add_action( 'wp_ajax_nopriv_load_more_posts', 'load_more_posts' );
function load_more_posts(){
global $post;
$args = array('post_type'=>'klanten', 'posts_per_page'=> 4, 'offset'=> $_POST['offset']);
$rst=[];
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()):$query->the_post();
$rst[] = $post;
$post_thumbnail = get_the_post_thumbnail($post->id);
$rst['post_thumbnail'] = $post_thumbnail;
endwhile;
wp_reset_postdata();
$offset = $_POST['offset']+4;
endif;
wp_send_json_success(array('klanten'=>$rst, 'offset'=>$offset));
}
I got help from a colleague and he figured it out. I added this in my js-file (jQuery)
// Counter for logos
var logoCount = $('.logo__wrapper').length;
var counter = 12;
// Show only first 12 logos
$('.logo__wrapper:nth-of-type(1n+13)').addClass('is-hidden');
// Load more logos button click
$('#load_more_posts').on('click', function (e) {
// Loop hidden logo's
$('.logo__wrapper.is-hidden').each(function (i) {
// Hide button if no more logo's
if (counter++ === logoCount) {
$('#load_more_posts').hide();
$('.loadmore__end').toggle();
}
// Show next 12 logos
if (i < 12) {
$(this).removeClass('is-hidden');
}
// Break loop after 12 logos
else {
return false;
}
});
});

Wordpress AJAX search not working

I am trying to create a search functionality with AJAX so it will load posts. It currently does not show the results.
I took this code from another post and played around with it as the completed code was sent privately.
Any help would be greatly appreciated.
functions.php file code
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><?php the_title();?></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}}
Script (in functions.php)
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
html
<input type="text" name="keyword" id="keyword" onkeyup="fetch()">
<div id="datafetch">Search results will appear here</div>
You might want to update the method name to 'POST' as javascript is case sensitive
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
You also might want to do an async call which needs callback as above approach will do synchronous call. Check this answer for callback approach
jQuery: Return data after ajax call success
there are some typos in your code like an extra } and a mising } later in php code. Please try:
functions.php
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><?php the_title();?></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch_search() {
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
html
<input type="text" name="keyword" id="keyword" onkeyup="fetch_search()">
<div id="datafetch">Search results will appear here</div>

Passing Php Variable to another variable using ajax?

I have this JS/jQuery code
window.onload = function(){
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php",
type: "GET",
dataType: "html"
//data: {$lastid},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
EDIT: This is the method where I get the $lastid.
<?php
function woocommerce_dashboard_recent_orders() {
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'ASC',
'post_type' => 'shop_order',
'post_status' => 'publish'
);
$orders = get_posts( $args );
if ($orders) :
echo '<ul class="recent-orders">';
foreach ($orders as $order) :
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
endforeach;
$lastid = $order->ID;
echo '</ul>';
else:
echo '<p>' . __( 'There are no product orders yet.', 'woocommerce' ) . '</p>';
endif;
}
?>
That calls a php file called test.php.
test.php
<?php
//woocommerce_dashboard_recent_orders_realtime();
/**
* Init the dashboard widgets.
*
* #access public
* #return void
*/
function filter_where( $where = '' ) {
$oid = 2100;
$where = " AND ID > $oid";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'shop_order',
'post_status' => 'publish',
'suppress_filters' => FALSE
);
$orders = get_posts( $args );
if ($orders) :
foreach ($orders as $order) :
//echo " $order->ID";
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
//echo (gettype($time3));
endforeach;
endif;
//}
?>
What I want to do is to pass the $lastid from the javascript to the test.php file and receive it as something like $lastid also.
I know I should post, but I'm having trouble using it. Can anyone lead me to the right method?
My CODE now
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" >
window.onload = function(){
//setInterval(function(){
//var lastid = '<?php echo $lastid; ?>';
//alert(lastid);
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php",
type: "POST",
dataType: "html",
data: { lastid : '<?php echo $lastid; ?>'},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
//addElement();
//},1000);
setInterval(function(){
},1000);
}
</script>
<?php
function woocommerce_dashboard_recent_orders() {
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'ASC',
'post_type' => 'shop_order',
'post_status' => 'publish'
);
$orders = get_posts( $args );
if ($orders) :
echo '<ul class="recent-orders">';
foreach ($orders as $order) :
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
endforeach;
$lastid = $order->ID;
echo '</ul>';
else:
echo '<p>' . __( 'There are no product orders yet.', 'woocommerce' ) . '</p>';
endif;
}
?>
<?php
function filter_where( $where = '' ) {
$oid = 2110;
$where = " AND ID > $oid";
return $where;
}
$lastid = $_GET['lastid'];
add_filter( 'posts_where', 'filter_where' );
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'shop_order',
'post_status' => 'publish',
'suppress_filters' => FALSE
);
$orders = get_posts( $args );
echo "LAST ID: $lastid";
if ($orders) :
foreach ($orders as $order) :
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
endforeach;
endif;
remove_filter( 'posts_where', 'filter_where' );
//}
?>
I'm not sure if I understand if I understand your question, but it seems like your first page has already evaluated $lastId, most likely from an insert query... and you want to also set it to a javascript variable, while also using post method. Assuming all that this is how I would for the first page
<script>
var $lastid = <?php echo $lastid ?>;
...
window.onload = function(){
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php",
type: "POST",
dataType: "html"
data: {"lastid":$lastid},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
....
</script>
Then on the second page use this to access the post
<?php
$lastid = $_POST['lastid'];
?>
That is how you do post in php hope this helps.
Try the following in the original code
...
url: "../wp-content/plugins/woocommerce/admin/test.php?lastid=2098"
...
Then in test.php, access the variable using
$lastid = $_GET['lastid'];
There are several other ways that this can be done, this is just a quick and dirty method.
1. Send the variable:
Change:
//data: {$lastid},
to:
data: { lastid : '<?php echo $lastid; ?>'},
2. Get variable in test.php:
$lastid = $_GET['lastid'];
window.onload = function(){
var lastId = <?php echo $lastId; ?>;
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php" + "?lastid=" + lastId,
type: "GET",
dataType: "html"
//data: {$lastid},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
on test.php add this line
$lastId = $_GET['lastid'];

Categories

Resources