0

I am using admin ajax request in wordpress plugin to access a function inside php class.

But, it is giving 400 bad request error:

my class file name: class.ajaxtest.php

ajaxtest_PLUGIN_URL is defined in main plugin php file as plugin_dir_url(FILE)

<?php


class ajaxtest
  {
      // Stated whether the plugin is initiated or not

      private static $initiated = false;

      // The init function

      public static function init()
      {
          if (!self::$initiated) {
              self::init_hooks();
          }

          // Start the session if it doesn't exist yet

          if (!session_id()) {
              session_start();
          }

          return;
      }

      private static function init_hooks()
      {
          self::$initiated = true;

          // Add hooks/actions

          add_action("wp_enqueue_scripts", ["ajaxtest", "euqueue_scripts"]);

          add_action("wp_ajax_nopriv_add_favorites", [
              "ajaxtest",
              "add_favorites",
          ]);

          add_action("wp_ajax_add_favorites", ["ajaxtest", "add_favorites"]);

          // Register stylesheets
      }

      // Enqueue the scripts for Wordpress

      public static function euqueue_scripts()
      {
          wp_register_script(
              "ajaxtest_fav_script",
              ajaxtest_PLUGIN_URL . "favjs.js",
              ["jquery"]
          );
          wp_localize_script("ajaxtest_fav_script", "ajaxtest_Ajax", [
              "ajaxurl" => admin_url("admin-ajax.php"),
          ]);

          wp_enqueue_script("ajaxtest_fav_script");
      }

      // add favorite properties
      public static function add_favorites()
      {
          echo "success";
          wp_die();
      }
  }

my jquery script name: favjs.js

jQuery(document).ready(function()
{
jQuery(".ajaxtest-fav-output").click(function(e){
    e.preventDefault();
    
    jQuery.ajax({
   url: ajaxtest_Ajax.ajaxurl,
 type: 'POST',
 dataType:'json',
data: {
'action':'add_favorites'
},
success: function(response) {
 alert(response);
}
});

});
   }); 

I tried everything but couldn't make it work. it is always giving 0 as output.

please help me.

thanks

4
  • What have you tried to resolve the problem? Where are you stuck? Does your server's error log tell you more about this problem? If not, check whether a higher error reporting level of PHP helps
    – Nico Haase
    Commented Mar 21, 2023 at 9:30
  • I did checked logs, there is no error displayed. ajax is not able to access static function inside a static class. if I move the function to another php script. it is works.
    – Rahul B
    Commented Apr 6, 2023 at 14:22
  • "ajax is not able to access static function inside a static class" - what does that mean? AJAX does not care about static functions or classes
    – Nico Haase
    Commented Apr 6, 2023 at 14:29

0

Browse other questions tagged or ask your own question.