Widget Javascript code (ajax)

I have a widget like this:

class test_widget extends WP_Widget{

  function test_widget(){
    $widget_ops = array('description' => 'test widget');
    $this->WP_Widget(false, 'Test', $widget_ops);

    add_action('init', array(&$this, 'ajax'), 99);

    // include in jQuery(document).ready()
    add_action('jquery_init', array(&$this, 'js'));
  }

  function js(){
    // get settings from all widget instances
    $widget_settings = get_option($this->option_name);

    // identify this instance
    foreach($widget_settings as $instance => $options):

      $id = $this->id_base.'-'.$instance;
      $block_id = 'instance-'.$id;

      if (is_active_widget(false, $id, $this->id_base)): ?>

      $("#<?php echo $block_id; ?> .button").click(function(){

        $.ajax({
          type: "GET",
          url: "<?php echo get_bloginfo('url'); ?>",
          data: { id: "<?php echo $block_id; ?>",
                  some_data: "<?php echo $options['some_widget_option']; ?>",
                  my_widget_ajax: 1 },
          success: function(response){
             alert(response);
             // yey
          }
        });
        return false;

      });

      <?php endif;
    endforeach;
  }

  function ajax(){
    if(isset($_GET['my_widget_ajax'])):

      $some_data = esc_attr($_GET['some_data']);

      echo $some_data;
      exit();
    endif;
  }

  function widget($args, $instance){
    // the widget front-end

  }

  function update($new_instance, $old_instance){
    // update form
    return $instance;
  }

  function form($instance){
    // the form
  }
}

Basically there’s a button in it which triggers a ajax request that retrieves some info…

Read More

As you can see the only way I could add the ajax function was by hooking it to the init tag, and the js to a theme function that handles the javascript.

The problem is that this only works when the widget is present in a sidebar.
And I also need it to work when I call this widget with the_widget() function, for eg. inside a page. I don’t know how could I retrieve the widget options to pass them in the javascript code…

Any ideas?

Related posts

Leave a Reply

1 comment

  1. The problem is that this only works when the widget is present in a sidebar.

    If you need some code to run independently from widget, I reason it makes sense to add that code separately from widget class.

    And I also need it to work when I call this widget with the_widget() function, for eg. inside a page. I don’t know how could I retrieve the widget options to pass them in the javascript code…

    That function takes instance array with widget data. I am not sure about your specifics, but I thinks you can pass whatever you need in there.

    Directly called widget has no data, other than passed in instance (or retrieved by itself).