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.

In a woocommerce’s project, How to update the cart quantity with ajax?

I’m building my own woocommerce theme with an HTML template that I bought for it. The question is: how can i update the cart’s label text with the ajax when a new product is added?

See my code to display the cart’s count:

<span class="cart_count" name='update_cart'><?= wc()->cart->cart_contents_count?></span> 

The button’s code to add a new product to the cart:

<li class="add-to-cart">   <a product-id="<?= $  featured_product->id ?>" href="#" class="single_add_to_cart_button">     <i class="icon-basket-loaded"></i>   </a> </li> 

the add-cart.php function:

<?php  function woocommerce_ajax_add_to_cart_js() {   if (function_exists('is_product') && is_product()) {       wp_enqueue_script('woocommerce-ajax-add-to-cart', plugin_dir_url(__FILE__) . 'assets/ajax-add-to-cart.js', array('jquery'), '', true);   } } add_action('wp_enqueue_scripts', 'woocommerce_ajax_add_to_cart_js', 99);  add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart'); add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');  function woocommerce_ajax_add_to_cart() {             $  product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($  _POST['product_id']));             $  quantity = empty($  _POST['quantity']) ? 1 : wc_stock_amount($  _POST['quantity']);             $  variation_id = absint($  _POST['variation_id']);             $  passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $  product_id, $  quantity);             $  product_status = get_post_status($  product_id);              if ($  passed_validation && WC()->cart->add_to_cart($  product_id, $  quantity, $  variation_id) && 'publish' === $  product_status) {                  do_action('woocommerce_ajax_added_to_cart', $  product_id);                  if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {                     wc_add_to_cart_message(array($  product_id => $  quantity), true);                 }                  WC_AJAX :: get_refreshed_fragments();             } else {                  $  data = array(                     'error' => true,                     'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($  product_id), $  product_id));                  echo wp_send_json($  data);             }              wp_die();         }  ?> 

the ajax-add-to-cart.js :

(function ($  ) {   $  (document).on("click", ".single_add_to_cart_button", function (e) {     e.preventDefault();      var $  thisbutton = $  (this),       product_qty = 1,       product_id = $  thisbutton.attr("product-id") || id,       variation_id = 0;      var data = {       action: "woocommerce_ajax_add_to_cart",       product_id: product_id,       product_sku: "",       quantity: product_qty,       variation_id: variation_id,     };      $  (document.body).trigger("adding_to_cart", [$  thisbutton, data]);      $  .ajax({       type: "post",       url: wc_add_to_cart_params.ajax_url,       data: data,       beforeSend: function (response) {         $  thisbutton.removeClass("added").addClass("loading");       },       complete: function (response) {         $  thisbutton.addClass("added").removeClass("loading");       },       success: function (response) {         if (response.error & response.product_url) {           window.location = response.product_url;           return;         } else {           $  (document.body).trigger("added_to_cart", [             response.fragments,             response.cart_hash,             $  thisbutton,           ]);         }       },     });      return false;   }); })(jQuery); 

I’ve already tried adding a script to the wp_footer:

jQuery('div.woocommerce').on('change', '.qty', function() {   jQuery("[name='update_cart']").prop("disabled", false);   jQuery("[name='update_cart']").trigger("click"); }); 

but I actually don’t know what dom element should be that div.woocommerce.

How to authenticate using JWT by ajax?

As WordPress REST API Doc said, the authentication by for REST API can be done by JWT (https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/)

The recommended plugin in the documentation is JWT Authentication for WordPress, but this plugin has not been updated for 1 year.

My question is, is this plugin still safe to use? if not, how can I auth using JWT by ajax?

Error loading wp_editor via ajax in wordpress

I needed help. I’m creating a page external to wordpress and needed to add wp_editor. Here is a simplified example of my code:

<?   require('../wp-blog-header.php');   define('WP_USE_THEMES', false);   ...   <body>     <button onclick="get_editor_ajax()"></button>     <div id="editor_text"></div>     ...       function get_editor_ajax(){         ...         success: function(resp){           jQuery("#editor_text").html( resp );         }         ...       }     ...   </body> ?> 

function.php

function test_editor_text(){   wp_editor($  content, $  editor_id);   _WP_Editors::enqueue_scripts();   print_footer_scripts();   _WP_Editors::editor_js();   wp_die(); } add_action('wp_ajax_test_editor_text', 'test_editor_text'); 

Partly it’s working, but I have problems. 1st – clicking on the button “get_editor_ajax ()” makes the element below (attachment img) appear at the end of the page.

enter image description here

2nd – The add media button does not work. I believe it is because the necessary scripts are missing. One time, my page doesn’t use a theme, it doesn’t load wordpress scripts.

Note: When calling the get_editor_ajax () function more than once, I noticed that codes are being added before the closing of as in this other attached image.

enter image description here

I need help with these two problems. Thanks in advance.

Ajax call of WordPress function

Can someone show me a good example of how to call a PHP function with Ajax? I’m trying to save an image gallery (with dynamic number of images) to database in the admin settings section. The below code is incomplete or maybe with some errors. Please show me a good example or a better way:

Save Changes

function jsAddSettingsFields(){      var elements = document.getElementsByTagName("img");     var urlsdata = new Array();      for (var i = 0, element; element = elements[i++];) {         if (elements[i].id == "idGalPic") {              urlsdata[i] = elements[i].src;  //now we have all image urls in array, now need to call add_settings_fields               var data = {                     action: 'php_addsettingsfields',                     p_urls: urlsdata //I think i need to JSON this                 };              jQuery.post( "", function( data ) );              //https://api.jquery.com/jQuery.post/         }     }  }//end of js function 

//PHP part:

        function php_addsettingsfields_callback() {              $  pic_urls = $  _POST['p_urls'];  //De-JSON-fy this variable              foreach ($  pic_urls as &$  url) {                 add_settings_field($  url);             }         add_settings_field(             'pic_url_id', // ID - slug name of field             '', // Title              array( $  this, 'pic_gal_callback' ), // Callback             'TestPlugin', // Page             'setting_section_id' // Section ID - slug name of page                  );         public function pic_gal_callback()       {            <input type="hidden" id="idPic" name="idPic" value=$  url>          }           //after all hidden fields(with gallery pic urls) are added to setting section submit the page and save the gallery urls to database 

How to load jQuery with Ajax in WP version 5.3.2?

I am building a custom theme and using wp_enqueue_scripts to load a custom JS file for a specific page template. As you can see I declared jquery as a dependency…

function enqueue_theme_scripts() {   if (is_page_template('template-contact.php')) {     wp_enqueue_script(       'template-contact-js',       get_bloginfo('template_directory') . '/template-contact.js',       array('jquery'),       false,       true     );   } } add_action('wp_enqueue_scripts', 'enqueue_theme_scripts'); 

This is what I have in the JS file…

(function($  ) {   $  (document).ready(function() {     console.log($  );     console.log($  .ajax);     }); })(jQuery); 

This is what the ‘console’ tab shows…

Screenshot of Chrome Inspector console tab

jQuery is loaded, but the $ .ajax method is not included.

This is what the ‘sources’ tab in the Inspector shows…

screenshot of jQuery 3.4.1 loaded in Chrome's inspector

As you can see it is loading jQuery version 3.4.1, but line 48 seems to indicate that ajax is being removed. How do I get jquery to load with the ajax method included?

AJAX Call Via Vanilla JavaScript In WordPress Plugin Development

I ama newbie in WordPress Plugin development in which I have some HTML form on the main plugin page that will get the data from the admin who is logged in and a back page where I have some different functions in PHP like to get information from the database etc. To explain in detail, here is the code…

Main Plugin File:

<?php /* Plugin Name: WP Testing Plugin Plugin URI: http://www.wordpress.org/WP-Testing-Plugin Description: A Detailed Description About This Plugin. Author: Muhammad Hassan Version: 0.1 Author URI: http://www.wordpress.org */  /*____________WP Testing Plugin Admin/Script_____________*/ function wp_testingPlugin_admin() {     echo '         <form id="searchForm" onsubmit="return searchData(this)">             <input name="WhatToSearch" type="text" />             <input type="submit" value="Search"/>             <input type="reset" value="Reset"/>             <div id="showReturnData"></div>         </form>     ';     echo '         <form id="infoForm" onsubmit="return searchInfo(this)">             <input name="WhatToKnow" type="text" />             <input type="submit" value="Search"/>             <input type="reset" value="Reset"/>             <div id="showReturnInfo"></div>         </form>     ';      echo '         <script type="text/javascript">             function searchData(incomingForm) {                 // Confirmation To Add A Data                 var answer = confirm("Are You Sure Want To Search?");                 if (answer){                     // If User Click Ok Then Execute The Below Code                          var FD = new FormData(incomingForm); // Get FORM Element Object                     FD.append("Function", "DataFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File                     var ajx = new XMLHttpRequest();                     ajx.onreadystatechange = function () {                         if (ajx.readyState == 4 && ajx.status == 200) {                             document.getElementById("showReturnData").innerHTML = ajx.responseText;                                      }                     };                     ajx.open("POST", "'.plugin_dir_url( __FILE__ ).'my_functions.php", true);                     ajx.send(FD);                     document.getElementById("showReturnData").innerHTML = "<div class="error">ERROR: AJAX Did Not Respond.</div>";                 }                 return false; // For Not To Reload Page             }               function searchInfo(incomingForm) {                 // Confirmation To Add A Data                 var answer = confirm("Are You Sure Want To Search?");                 if (answer){                     // If User Click Ok Then Execute The Below Code                          var FD = new FormData(incomingForm); // Get FORM Element Object                     FD.append("Function", "InfoFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File                     var ajx = new XMLHttpRequest();                     ajx.onreadystatechange = function () {                         if (ajx.readyState == 4 && ajx.status == 200) {                             document.getElementById("showReturnData").innerHTML = ajx.responseText;                                      }                     };                     ajx.open("POST", "'.plugin_dir_url( __FILE__ ).'my_functions.php", true);                     ajx.send(FD);                     document.getElementById("showReturnInfo").innerHTML = "<div class="error">ERROR: AJAX Did Not Respond.</div>";                 }                 return false; // For Not To Reload Page             }          </script>     '; //if you want only logged in users to access this function use this hook add_action('wp_ajax_searchData', 'searchData'); add_action('wp_ajax_searchInfo', 'searchInfo'); //if you want none logged in users to access this function use this hook add_action('wp_ajax_nopriv_searchData', 'searchData'); add_action('wp_ajax_nopriv_searchInfo', 'searchInfo');   } /*__________________________________________________________________*/   /*____________WP Testing Plugin Option_____________*/ //Adding "WP Testing Plugin" Menu To WordPress -> Tools function wp_testingPlugin() {     //  add_management_page( $  page_title, $  menu_title, $  capability, $  menu_slug, $  function);                  Menu Under Tools     add_management_page("WP Testing Plugin By Hassan", "WP Testing Plugin", 'activate_plugins', "WP-Testing-Plugin", "wp_testingPlugin_admin"); } add_action('admin_menu', 'wp_testingPlugin'); /*__________________________________________________________________*/ ?> 

And this is my_functions.php file.

<?php /****************************************************************************/ //Garb The Function Parameter /****************************************************************************/ $  Function = $  _POST['Function'];   /****************************************************************************/ // Run Search Function /****************************************************************************/ if ($  Function == "DataFunction"){      if(!isset($  _POST['WhatToSearch'])){         $  WhatToSearch = "Nothing";     } else {         $  WhatToSearch = $  _POST['WhatToSearch'];     }      echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$  WhatToSearch.".</div>"; }  /****************************************************************************/ // Run Another Function /****************************************************************************/ if ($  Function == "InfoFunction"){      if(!isset($  _POST['WhatToKnow'])){         $  WhatToKnow = "Nothing";     } else {         $  WhatToKnow = $  _POST['WhatToKnow'];     }      echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$  WhatToKnow.".</div>"; }  ?> 

But my code is not working and not hitting my_functions.php file even. Whats the problem here? Need basic step only to work in this patteren. Currently, I am not sure I am even implementing this correctly as I never used WP AJAX before. So right now, my objective is just to get a basic example working. I appreciate any suggestions on how to accomplish this.

Thank you!