Why is this Ajax not working?

I’m not sure if I am abusing WordPress and Ajax by doing it this way but WP and Ajax Codex a well as Plugin Development with Ajax do not seem to be very helpful. I have created the following Ajax situation:

(function($){   
    $(document).ready(function(){
        $('a').click(function(e){
          var el = $(this).prev('input[type="checkbox"]');
          if(el.is(':checked')){
               el.prop('checked',false);   
          }
          $.ajax({
              url  : "<?php echo CORETHEME_ADMIN_TEMPLATE_HELPER_URL . 'UncheckPackageThemeHelper.php'; ?>",
              type : 'POST',
              data : { 'element_name' : el.prop('name') },      
              success: function(result){
                console.log(result);
              },
              error: function(jqXHR, textStatus, errorThrown ){
                console.log(jqXHR, textStatus, errorThrown);
              } 
          });
          e.preventDefault();
        });
    }); 
 })(jQuery);

Which states that: When a link is clicked, we unchecked the check box and pass that element name to a class.

Read More

Everything works until you see the unset_package method in my class

class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{

    private $_element_name = null;

    public function __construct(){
        if(isset($_POST["element_name"])){
            $this->_element_name = $_POST["element_name"];
            $this->unset_package();
        }
    }

    public function unset_package(){
        $option = get_option($this->_element_name);
        if(isset($option)){
            $option = '';
        }
    }
}

new CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper();

Everything works until the get_option – I get 500 errors. meaning that the get_option() method doesnt exist – in this instance. I think If I take out the get_option and the rest of it and replace the contents of unset_package

with echo json_encode($this->_element_name); everything works and I get the element name given back.

Can some one explain why this isn’t working and maybe show me the proper WordPress way? The Documentation was very confusing to say the least.

Related posts

1 comment

  1. When you load a php file directly via an ajax request (UncheckPackageThemeHelper.php) it’s loaded outside the context of WordPress, so no WordPress core functions are available.

    All WordPress ajax requests should be routed through admin-ajax.php. You can print the URL with the function admin_url:

    admin_url( 'admin-ajax.php' )
    

    When admin-ajax.php is loaded, WordPress is bootstrapped, so you’ll now have access to core functions.

    The last step is to pass an action parameter from your javascript, and map that action to the function you want called when the action is executed:

    add_action( 'wp_ajax_my_action', 'my_action_callback' );
    

Comments are closed.