SACK of AJAX

September 30, 2008 | AJAX, Wordpress | 4 comments

For those of you that don’t know what AJAX is, please read my simple tutorial here. For those of you that do, carry on reading…

I wanted to use some AJAX within a wordpress plugin i’m writing called Your Responder to handle a form submission and feedback without having to refresh the page.

I was reading through the Codex looking for anything AJAX related and came across a bundled script called SACK. It actually stands for Simple Ajax Code Kit and i’m happy to say it does exactly what it says on the tin. I haven’t even looked at the advanced features yet but a basic ajax request can be made in a few small lines of easy to follow code.

The full wordpress example is here but I thought I would give a explanation of my own…

The first stage is to incorporate the SACK library. Of course there is a special way to do this in wordpress but it’s very simple:

wp_print_scripts(array('sack'));

Copy that somewhere into your plugin and it does the same as putting a ‘<script src=”” />’ into the head of the html page.

Next comes the actual call:

  var mysack = new sack("www.yoursite.com/wp-content/plugins/myplugin_ajax.php");    

  mysack.execute = 1;
  mysack.method = 'POST';
  mysack.setVar("vote", vote_field.value);
  mysack.onError = function() { alert('Ajax error in voting'); };
  mysack.runAJAX();

  return true;

Does it look complicated? If your answer is yes then I urge you to have a look at the actual AJAX code to accomplish a POST request. I shall go through this line by line to help it make a little more sense:

The first line sets up a new variable called mysack which is actually an occurence of the mysack object. It allows you to call any function from the library and set up variables within it without interfering with any other SACK requests on the same page. The url in the call is an absolute link (I have yet to test with relative links) to the PHP script that the request will be sent to, much like the ‘<form action=””>’ tag.

Ignore the execute line. For a simple example just appreciate it has to be there. The method line is directly the same as ‘<form action=””>’ so can accept, to my knowlege,  either GET or POST.

The next line ‘setVar’ you can duplicate for each field you want to send to your back end script. So if you wanted to send something that will appear to the server as $_POST[‘field1’], you simply write:

mysack.setVar("field1", document.getElementById("input_field_id").value);

Remember this is a JS function so where I put my document.getElement… call, you can write anything that javascript understands (although to keep it tidy, it’s probably best to sort it out earlier and store in a variable).

On error is probably best to leave empty unless you want to show a div on the screen saying something like ‘invalid request’. Remember this will be shown to your site users to an alert box probably isn’t the best approach.

Finally we fire off the request using runAJAX().

The PHP backend

At this stage your user is looking at your site and has, in some way or another, fired off an AJAX request. If the request was intentional (ie: not triggered by something passive) then they most likely expect something like a message back from the server or event to occur.

In the above example we declared a new instance of the SACK library with the url we want to send a request to (www.yoursite.com/wp-content/plugins/myplugin_ajax.php). The PHP script we need to write obviously needs to be at this location.

There are two things you really need to remember with this:

  1. AJAX requests accept anything echoed as it’s response and will throw an error if it’s not sent proper JS code.
  2. Use a PHP ‘die’ statement to send your response to the client.

All the first one means is that, when testing, a print_r($_POST); will not work properly and if you can see AJAX/JS errors (via Firefox and Firebug or similar) then you will most likely be prompted to fix your code.

The second one is simply a recommendation from the WordPress development team which I agree with. If you concatenate your response JS code into a variable and then run a ‘die’ with your variable as the argument then it’s likely to work.

See the following example of what would be your ‘myplugin_ajax.php’ file:

<?php
if (isset($_POST['vote']) {
    //Perform some DB bits here
    $feedback = 'alert("Your vote was successfully recorded");';
    die($feedback);
}
?>

If you now understand what to do then I recommend trying it before reading the next section because it will only confuse matters if you are just getting to know either AJAX or WordPress.

We are checking in $_POST for a variable called ‘vote’ and notice there is no ‘else’ statement. We don’t need an else unless you want to report error messages back to the server which in this case I don’t.

WordPress doesn’t allow immediate access to any files inside it’s directory structure so things like Database access and shared function usage won’t be possible. The only way we can make this work is to incorporate the handing code into the main plugin itself. Simply add your version of this code to your main plugin PHP file which will be called from within wordpress.

This also means that your setup URL for SACK will simply be the homepage of your blog. This will work because wordpress scans it’s plugin directory when it initiates its framework looking for hooks. As long as your plugin is active it will run your logic. The die statement will also stop that instance of the script from running hence the if statement with no else.

Good luck and let me know if you need any help, spot a mistake or just want to say something 🙂

A Donate Button!

4 Comments

  1. Alois Kratochwill

    Great article, thanks!
    SACK works great for me but how can I get sending “+” and € (€) to work?

    Alois

    Reply
    • Sean

      Hi Alois, great stuff. It’s a really nice library isn’t it. Regarding the characters.What is it sending instead of those you mentioned. I think you have the right idea with the special character encoding. Use € instead?

      Let me know
      thanks
      Sean

      Reply
  2. Rupesh

    will you tell me about requestFile method in SACK??

    Reply
    • Sean

      Hi Rupesh, I think that we can ignore that variable seeing as we are setting the request file in the constructor new sack(requestFile_here)

      thanks
      Sean

      Reply

Submit a Comment

Your email address will not be published.

CommentLuv badge

About this site and Sean Barton

Picture of Sean
Sean Barton is a Freelance Website Developer in Crewe, Cheshire. He is a Full Stack Developer but with extensive experience in Wordpress and other Frameworks. He is the Co-Founder of SitePresser, Layouts Cloud and Page Builder Cloud among other things..
This site was set up in 2008 as a tutorial and scripting resource for the PHP language and Wordpress.
Find out more about Sean on the About Me page or use the Hire Me page to get in touch. For more information about Sean's work take a look at the Portfolio

SitePresser is the plugin that packages child themes and layout packs for sale. Works with Divi and Elementor.