Monday, February 09, 2009

Ajax and WordPress - A Simple Approach To Integration

Tonight, the app I was working on was crying out for a small feature which Ajax would work perfect for. So, I busted out jQuery and wrote some JavaScript like*:

 function addToAddressBook(name, phone) {
   jQuery('#spinner').show();
   jQuery.post("http://myserver.com/ajax/add_addr.php", 
              { name: name, phone: phone }, 
             function(data) {
               jQuery('#spinner').hide();
               // do more stuff with data
             }, "json");
 }

And then it hit me, my script add_addr.php isn't part of WordPress, so inside of it I won't be able to access WordPress details like the current user. Which in this case, I wanted to do, because I wanted to add the address to the particular user that is logged in.

The solution turned out to be a Google Search Away. All I need to do, was put the following at the top of add_addr.php:

 <?
  require_once('../wp-blog-header.php');
  ...
  // works because we've imported the environment above
  $user = wp_get_current_user();
  ...
 ?>

Turns out, WordPress integrates nicely with 3rd party scripts. One more reason to like WordPress, I guess.

*It wasn't really an address book application. I could tell you about what it really was, but then I'd have to kill you.

1 comment:

  1. Nice one guys! We might try to work a reference to this one into our blog post about integrating wordpress later next week.

    integrating wordpress

    ReplyDelete