Trying to run a add_action within a function to run a woocomerce function on a ajax request

I am able to get a ajax request to work properly on a woocommerce checkout form page, now I want to update the price of the checkout in that ajax request. My add_action is in the function that is fired by the ajax request.

This is all done in a custom plugin as well

Here is my code this far, it doesn’t seem like the function request_gift_card ever fires

 function gift_card_redeem(){      if(!empty($  _SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($  _SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {     error_log("test !empty");          add_action( 'woocommerce_before_calculate_totals', 'request_gift_card', 99 );      function request_gift_card($  cart_object){       if( !WC()->session->__isset( "reload_checkout" )) {           /* Gift wrap price */           $  additionalPrice = 5;           error_log($  cart_object);           foreach ( $  cart_object->cart_contents as $  key => $  value ) {               if( isset( $  value["embossing_fee"] ) ) {                   // Turn $  value['data']->price in to $  value['data']->get_price()                   $  orgPrice = floatval( $  value['data']->get_price() );                   $  discPrice = $  orgPrice + $  additionalPrice;                   $  value['data']->set_price($  discPrice);               }           }       }     }      $  result['type'] = "success";     $  result = json_encode($  result);     echo $  result;   }   else {     error_log("test else");       header("Location: ".$  _SERVER["HTTP_REFERER"]);   }    die(); } 

WordPress update_comment_meta onclick not working with Ajax

I’m attempting to update_comment_meta via Ajax call in WordPress, but no data is returned and the comment_meta field is not being updated.

Fun.php

add_action( 'wp_enqueue_scripts', 'comment_voting_enqueue_scripts' ); function comment_voting_enqueue_scripts() {   wp_enqueue_script( 'comment_meta_voting-js', get_template_directory_uri() . '/js/ajax-vote.js', array( 'jquery' ), '0.5', false );   wp_localize_script( 'comment_meta_voting-js', 'commentMetaVoting', array(     'ajaxurl' => admin_url( 'admin-ajax.php' ),   ) ); } add_action( 'wp_ajax_nopriv_comment_meta_voting', 'comment_meta_voting' ); add_action( 'wp_ajax_comment_meta_voting', 'comment_meta_voting' );  function comment_meta_voting() {     $  comment_id = $  _POST['vote'];     $  vote_total = get_comment_meta($  comment_id , 'vote', true);     ++$  vote_total;     update_comment_meta($  comment_id , 'vote', $  vote_score );     die(); } 

ajax-vote.js

(function($  ) {     'use strict';     $  (document).on('click', '.sl-button', function() {         var button = $  (this);         var cmnt_id = button.attr('data-post-id');         var security = button.attr('data-nonce');              $  .ajax({                 type: 'POST',                 url: commentMetaVoting.ajaxurl,                 data : {                     action : 'comment_meta_voting',                     post_id : cmnt_id,                     nonce : security,                 },                 success: function(response){                     console.log('tst');                 }             });          return false;     }); })(jQuery); 

and in wp_list_comments callback i add core function where i want to show the link to call:

     <a href="<?php echo admin_url( 'admin-ajax.php?action=comment_meta_voting' . '&cmnt_id=' . $  commentid . '&nonce=' . $  nonce ); ?>" class="sl-button" data-nonce="<?php echo $  commentid ; ?>" data-post-id="<?php echo $  commentid ; ?> ">click</a> 

Finally i get console.log(‘tst’); in thee console.. so i think its correct, no data is returned and the comment_meta field is not being updated..

any help?

jQuery Ajax not loading page with ACF fields

I’m using the following jQuery code to load contents from a template part into another on click. Without the ACF PHP tags, it works. However, when I add these tags in <?php the_field('field_name'); ?> it throws a 500 (Internal Server Error) error. Does anyone have a solution for this, please?

    var baseUrl = "http://projectname:8888/wp-content/themes/custom-theme"      $  (".cross__functional").click(function (e) {         e.preventDefault();         console.log('cross functional Clicked')         $  ("#keContent").load(baseUrl + "/template-parts/components/filename.php");     }); 

WordPress ajax serial processing of and sending

I want to install/activate plugins via ajax.But i want to add a loading class on plugins list item which is being installing or activating. In jquery If i want to do it i need to write a lot bunch of code there.For example I have 4 plugins to install.So i have to first, send first ajax request to install first plugin then when a response comes I send second request in success block but its too time consuming. I want to know if there is any easy solution. Or in php file can i send a response back then continue installing 2nd one. Is that possible??

Ensure function has completed before allowing another Ajax call

I am updating an array saved in a users meta field using an ajax function.

The values added to the array are taken from the data-attributes within the tags which also act at the trigger to make the ajax call.

Whilst the function works 95% of the time, it can be a bit hit and miss whether the values save or not. I suspect this is because a user can fire these ajax calls too quickly and not give enough time for the original function call to save and update the meta field.

What would be the best method to ensure the ajax triggered function of updating the meta field value has been completed before allowing the function to run again?

Hope this makes sense – needless to say, please let me know if you need any more info.

Thanks in advance!!

Sample HTML

<div id="rjb_slots" class="slots">   <h5>Mon, 24th Aug 2020</h5>   <div class="slot">     <span class="time">10:30</span>     <a class="book" data-timestamp="1598265000" href="#"></a>   </div>   <div class="slot">     <span class="time">11:00</span>     <a class="booked" data-timestamp="1598266800" href="#"></a>   </div>   <div class="slot">     <span class="time">11:30</span>     <a class="booked" data-timestamp="1598268600" href="#"></a>   </div>   <div class="slot">     <span class="time">12:00</span>     <a class="book" data-timestamp="1598270400" href="#"></a>   </div>   <div class="slot">     <span class="time">12:30</span>     <a class="booked" data-timestamp="1598272200" href="#"></a>   </div>   <div class="slot">     <span class="time">13:00</span>     <a class="book" data-timestamp="1598274000" href="#"></a>   </div>   <div class="slot">     <span class="time">19:30</span>     <a class="book" data-timestamp="1598297400" href="#"></a>   </div> </div> 

Ajax .js

$  ('.slot').on('click', 'a.book', function(e) {   e.preventDefault();    var user   = $  ('#rjb_day').attr( 'data-user' );   var stamp  = $  (this).attr( 'data-timestamp' );       // console.log(bookCap);      $  (this).removeClass('book').addClass('booked');    $  .ajax({     type: 'POST',     url: ajax_object.ajaxurl,     data: {         action: 'rjb_make_diary_slots',         user: user,         stamp: stamp     },     success: function(data) {       // This outputs the result of the ajax request       console.log(data);     },     error: function(errorThrown){         console.log(errorThrown);     }   });      }); 

Function that updates the user metafield

add_action( 'wp_ajax_rjb_make_diary_slots', 'rjb_make_diary_slots' );  function rjb_make_diary_slots() {    $  user   = $  _POST['user'];    $  stamp  = array(               array(                  'rjb_cal_day'           => strtotime('today', $  _POST['stamp']),                 'rjb_cal_when'          => $  _POST['stamp'],                 'rjb_cal_position_id'   => '',                 'rjb_cal_candidate_id'  => ''               )             );    $  calendar   = get_user_meta( $  user, 'rjb_cal', true);   $  stamps     = !empty($  calendar) ? $  calendar : array();   $  new_stamp  = array_merge($  stamps, $  stamp);    usort($  new_stamp, function($  a, $  b) {     return $  a['rjb_cal_when'] <=> $  b['rjb_cal_when'];   });    update_user_meta( $  user, 'rjb_cal', $  new_stamp);    $  log = print_r($  stamp);    wp_die($  log);  } 

Example of a value stored in the rjb_cal user meta field

array (   [0] => array (     [rjb_cal_day] => 1598227200     [rjb_cal_when] => 1598266800     [rjb_cal_position_id] =>      [rjb_cal_candidate_id] =>    )   [1] => array (     [rjb_cal_day] => 1598227200     [rjb_cal_when] => 1598268600     [rjb_cal_position_id] =>      [rjb_cal_candidate_id] =>    )   [2] => array (     [rjb_cal_day] => 1598227200     [rjb_cal_when] => 1598272200     [rjb_cal_position_id] =>      [rjb_cal_candidate_id] =>    ) ) 

WP Ajax Function Always Returning undefined

What is the deal here?

JS FUNCTION ‘custom.js’

function validate() {     var email = jQuery("#billingemail").val();      if (isValidEmailAddress(email)) {         jQuery.ajax({             type: 'POST',             url: ajaxurl,             data: {"action": "custome_ajax_email_check", "guestemail": email },             success: function(data){                 data = jQuery.parseJSON(data);                 if(data.result) {                     alert('Email Exists');                     return false;                 } else {                     alert('Email Does Exists');                     return true;                 }             }         });     } else {         return false;     } } 

JS ON CLICK ‘custom.js’

 $  ('#mwb_logincoupon').on('click', '#validateguestemail', function (e) {         e.preventDefault();         validateemail = validate();          

PHP AJAX

add_action( 'wp_ajax_custome_ajax_email_check', 'custome_ajax_email_check' ); add_action('wp_ajax_nopriv_custome_ajax_email_check', 'custome_ajax_email_check');  function custome_ajax_email_check(){     $  email = $  _POST['guestemail'];      // do check     if ( email_exists($  email) ) {         $  response->result = true;     }     else {         $  response->result = false;     }      echo( json_encode( $  response));     wp_die(); } 

debugging the script the JS code goes into the success function, so far as even triggering off the alert('Email Exists').. but the return statement in the functon is never retrieved thus making validateemail always return undefined. Why?

Will Googlebot click a button/link to reveal AJAX content?

my client has to inform it’s customers about some new regulations that the Googlebot should NOT crawl. It is not possible to place this information on a separate page and disallow Google to crawl it. So the idea is to place a button/link on the page, that will AJAX-load the corresponding information only when the user clicks it. My assumption is, that Google is unable to click the link and crawl that specific AJAX content.

Am I right? And if yes, is there an official documentation that proofs my point on this?

Why, if a function accepts arguments, it fails on ajax calls?

I am trying to write a WP function to work with both ajax and direct calls, something like this:

PHP

function some_function($  var){     $  var = !empty($  var) ? $  var : $  _POST['var'];     echo $  var;          //or even      $  var = null;     echo 'something';      if(!empty($  _POST['action'])) wp_die(); } 

AJAX CALL

let ajaxurl = '███'; let data = {'action': 'somefunction','var':'foo')}; $  .post(ajaxurl, data, function(response) {console.log(response);}); 

WP use

add_action( 'wp_ajax_somefunction', 'some_function',10,1); add_action( 'wp_ajax_nopriv_somefunction', 'some_function',10,1); 

Another WP use

some_function('bar'); 

However, any time I place $ var as an accepted function argument, some_function($ var), my ajax calls start returning a 500 error. So, something like this

function some_function(){     $  var = !empty($  var) ? $  var : $  _POST['var'];     echo $  var; } 

works for ajax.

I tried looking up wp ajax & arguments, but the search results are always about the variables we pass through ajax, not the callback function arguments. The only thing I learned is that we have to add a number of accepted arguments into add_action()

What am I doing wrong?

Thank you.

…P.S. I found a funny workaround:

function some_function_ajax(){     $  var = $  _POST['var'];     some_function($  var); } function some_function($  var){     echo $  var; } // =) 

but still, what is the right way?

Can’t reset tax query using ajax sorting plugin?

I have created an ajax sorting feature that filters a custom post type "Music" and its all separated by Genres and Tags.. the sorting works fine until.. I deselect all options. I’ve tried to add "all" as the default and added in the JS that if the genre is "all" to include all the posts. Every thing else works as desired but I need to be able to reset the tax query or include all.

Here is that javascript:

jQuery(document).ready(function($  ){                var bgenre = $  (":checkbox[name=bgenre]");     var btags = $  (":checkbox[name=btags]");          jQuery.merge( bgenre, btags ).on( "change", function() {              var genre;     var tags;            var genrearray = [];         var tagsarray = [];                           $  (":checkbox[name=bgenre]:checked").each(function() {              genrearray.push($  (this).val());                          //genre = genrearray.join();                 genre = genrearray;                  });                          $  (":checkbox[name=btags]:checked").each(function() {              tagsarray.push($  (this).val());              tags = tagsarray.join();                     });              //  var tags = tagsarray.join();          if (genrearray.length < 1) {         genre = 'all';     }          data = {             'action': 'filterlist',             'genre': genre,             'tags': tags                      };           $  .ajax({             url : ajaxurl,             data : data,             type : 'POST',             beforeSend : function ( xhr ) {                  $  ('.bplaylist').html( 'Loading...' );                 $  ('.js-Genre').attr( 'disabled', 'disabled' );                              },             success : function( data ) {                 if ( data ) {                                                        $  ('.bplaylist').html( data.posts );                       $  ('.js-Genre').removeAttr('disabled');                     $  ( '.js-Tags' ).removeAttr('disabled');                                      } else {                     $  ('.bplaylist').html( 'No posts found.' );                 }             }         });     })     }); 

and here is the php

function ajax_filterlist_handler() {                       //$  tags = esc_attr( $  _POST['tags'] );            $  genre = $  _POST['genre'];             $  tags = $  _POST['tags'];                                $  args = array(             'post_type' => 'download',             'post_status' => 'publish',             'posts_per_page' => -1,             'orderby' => 'date',             'order' => 'DESC',             'tax_query' => array(),             'relation' => IN         );                        if ( isset( $  _POST['genre']) && $  _POST['genre'] !== 'all'   ) {         $  args['tax_query'][] = array(             'taxonomy' => 'genre',             'field' => 'slug',             'terms' => $  genre          ); }           if ( isset( $  _POST['genre']) && $  _POST['genre'] === 'all'   ) {          $  args['tax_query'][] = array(             'taxonomy' => 'genre'                                         );                  }     if ( !isset( $  _POST['genre']) ) {          $  args['tax_query'][] = array(              );                  }                        if( isset( $  _POST['tags'] ) ) {         $  args['tax_query'][] = array(             'taxonomy' => 'download_tag',             'field' => 'slug',             'terms' => $  tags         );     }                 $  posts = 'No Posts Available';          $  the_query = new WP_Query( $  args );               if ( $  the_query->have_posts() ) :             ob_start();              while ( $  the_query->have_posts() ) : $  the_query->the_post();             get_template_part( '/custom/template-parts/trackitem' );             endwhile;              $  posts = ob_get_clean();         endif;          $  return = array(             'posts' => $  posts         );          wp_send_json($  return);     }     add_action( 'wp_ajax_filterlist', 'ajax_filterlist_handler' );     add_action( 'wp_ajax_nopriv_filterlist', 'ajax_filterlist_handler' );    

Sorry if the code is jumbled mess at this point. I was following a tutorial and after I got it working. I kinda went on my own to try to figure out the reset and/or all option.