How to Pass WordPress Database Information to the Front-End for Javascript/Ajax

By Fábio Zaffani How ToThemesWordpress at 26 de January de 2012

Thats one of the nicest things I have recently come across while playing around with wordpress, i was currently trying to pass information from the database, dynamically, to the front end to use this information in ajax requests and dynamic validation with javascript.

The key, in this case my friends, is to use the wp_localize_script() function. With that function you will be able to output all the needed backend information in the front-end, all correctly wrapped in a logical javascript namespace.

Lets say I have a Shopping Site, and I want to create a dropdown with all the products. I also want that, when the user select something from the drop down, it will refresh and collect all this product information from the backend, all that through ajax.

To achieve that we should do this

wp_localize_script(
   'ProductJS',   // the script handle name
   'ProductInformation', // the javascript object that will hold the data
    array(
      'ajaxurl'          =>  admin_url( 'admin-ajax.php' ), // generate a nonce with a unique ID "plulzajax-post-comment-nonce"
      'productAjaxNonce' =>  wp_create_nonce( $this->_nonce ),
      'actionProduct'    =>  'product-ajax',
      'codeList'         =>  json_encode($this->_post->PlulzProduto->getCodeList())
    )
);

Explanation of each part of the code

ProductJS

The script handle name, is the name you gave to the script where you are inputing all your javascript code, by registering correctly it you make sure that all that back end information will be correctly inputed only in the pages the script that requires that information are loaded. For example, the code above will only be loaded when the bellow command is executed:

wp_enqueue_script( ‘ProductJS’, ‘$filenamepath/priceformat.jquery.js’);

ProductInformation 

Its the namespace where the information will be hold, so in order to use it in the javascript file, with the example above, you would do something like ProductInformation.somevariablename

The array that follows is the information that you want to use, above there were 3 information that I use for control purposes and only the last one is the information that I really need, I also make sure to send it converted in json , since it is an array, and I need the javascript to understand it correctly.

ajaxurl – its the php file of wordpress that handles ajax requests

productAjaxNonce – a unique code generated for each request to improve security

actionProduct – the action, I use this to know, in the backend, when this specific request is being made

codeList – this one I will use in the front end to generate the code list for the user, dinamically with javascript.

Any doubts fell free to post bellow!