Jun 9 2009

Adding Sack Ajax To Your WordPress Plugin’s Admin Page

Using my previous wordpress example plugin I’m going to demonstrate how to use ajax within the admin panel. WordPress uses the Simple AJAX Code-Kit (SACK) which is relatively easy to use and understand.

For this example I’m going to expand on my previous example and add a simple javascript function that queries some data from the server. WordPress forces us to do this in a roundabout way. First we have to add two new function hooks. One prints my javascript function in the scripts section of the admin panel and the other is the code that gets called by the ajax sack request.


//add my custom ajax function to the scripts section in the admin panel
add_action('admin_print_scripts', 'ajax_request');

//add data returning ajax refresh table function
add_action('wp_ajax_do_something', 'get_random_number');

The ajax_request function is a shell function for the javascript ajax call get_random_number_from_server which is our sack ajax request. Note that we are calling the admin-ajax.php script. This script will handle the calling of the get_random_number function for us because of the action defined above.


//This function will print out in the header section. 
//Put all your javascript in this function.
function ajax_request()
{
        //print out the sack ajax library
        wp_print_scripts( array( 'sack' ));  
  ?>
  <script type="text/javascript">
  //<![CDATA[
    
  function get_random_number_from_server()
  {
    //creates the sack object and 
                //gives it the url that it should request to.
    var mysack = new sack( '<?php 
                bloginfo( "wpurl" ); ?>/wp-admin/admin-ajax.php' );    
        
    mysack.execute = 1;   //execute whatever is returned
    mysack.method = 'POST';
    
    //Set POST fields
    mysack.setVar( "action", "do_something" );
        
    mysack.encVar( "cookie", document.cookie, false );
    mysack.onError = function() { alert('Ajax Error')};
    mysack.runAJAX();  //run the result

    return true;

  } // end of JavaScript function myplugin_ajax_elevation
  //]]>
  </script>
  <?php
  
}

This is the php function that is called by the javascript function above. It spits out a alert javascript function and then dies. Not sure why but it is recommended to die in this function.


//This is the server side code for the ajax sack request
function get_random_number()
{
  $minimum_number = 0;
  $maximum_number = 100;
  die("alert('".rand($minimum_number,$maximum_number)."');");
} 

This code can now be run like the following in your plugins admin page.


<input type='button' value='Get Random Number' 
onclick='get_random_number_from_server();'>

When the button is hit a popup with a random number in it will pop up. Here’s a link to the entire example plugin code.

Share

Jun 3 2009

10 Things To Know About JSON (JSON Javascript Examples)

I used JSON for the first time today and it’s really nothing special. I’ve heard about it a few times but never really given it much thought and theres no reason I should have. Here is the list of all you really need to know about this syntax for passing around name value pairs and arrays to javascript.

  1. JSON is an acronym for ‘Javascript Object Notation’.
  2. JSON is fast. Mostly because it is recognized natively by Javascript so there’s no processing overhead.
  3. JSON is an ordered list of name value pairs.
  4. JSON is so much easier to read and write than XML due to it’s simplicity.
  5. Apperently (Untested by me) data is formatted as JSON then Ajax can travel across domains.
  6. Almost every language used in web development either already has a JSON library or set of functions. If one doesn’t, then creating functions is a trivial task.
  7. ‘var jsonObject = { ‘cody : ‘taylor’ };’ is referenced by ‘jsonObject.cody’ which gives us ‘taylor’.
  8. ‘var jsonObect = {‘javascript’ : {‘json’ : ‘not xml’ };’ is referenced by ‘jsonObject.javascript.json’ which gives us ‘not xml’.
  9. You can also reference the JSON object as if it was an associative array like ‘jsonObject[‘cody’]’ or ‘jsonObject.javascript[‘json’]’ which gives the same values as previously.
  10. If you don’t want to use key/value pairs you can define a normal data array. ‘jsonObject = {‘arrayOfData’: {‘numbers’ : [‘1’, ‘2’, ‘3’]}};’ We use indexes for this dataset. Don’t use indexes for the collections defined in the ‘{ }’. ‘jsonObject.arrayOfData.numbers[1]’ will give us ‘2’.
  11. You can put functions in the dataset to pass around executable code.

So now you know basically all there is to know about JSON.

Share