Puddinq.com sharing knowledge

WordPress php variabele in javascript and ajax request

WordPress php variabele in javascript and ajax request

Once a page is loaded you can use Javascript to make an additional request for information. This requires a javascript file and a php function allowed to pass that information.

All you need

This article gives you all you need to make a plugin that can:

  1. Use a php variabele in a javascript file. (make it available)
  2. Make a javascript request to the server and get a php value in return.
  3. Use the php value in your page

To start you need..

  1. In wp-content/plugins/ you need to create a folder with a unique name. For this example we will use my-plugin.
  2. In this folder you need two files
    one php with the same name as the folder: my-plugin.php
    and one js (javascript): my-plugin.js

Start here with the php file

The code below should go in my-plugin.php

Freedom in creation
Improvements in user experience
If you want to you can

Have wordpress data in you javascript file
Access wordpress functions with javascript

* Plugin Name: My Plugin Name
* Plugin URI: http://mypluginuri.com/
* Description: A brief description about your plugin.
* Version: 1.0 or whatever version of the plugin (pretty self explanatory)
* Author: Plugin Author's Name
* Author URI: Author's website
* License: A "Slug" license name e.g. GPL12

// hook the my_plugin_ajax_setting to the allowed ajax requests
// 1. pud_ajax_remember_setting should be the same as the function name (3)
// 2. remember_setting last part of the hook name should be the same as the action in the javascript function.

add_action( 'wp_ajax_remember_setting', 'pud_ajax_remember_setting' ); // for loggedin users
add_action( 'wp_ajax_nopriv_remember_setting', 'pud_ajax_remember_setting' ); // for guests

// This is the function that will be called with ajax. You can put anything
// in it. In this case a session is started if it has not been already, and a
// value is add.
// If you want to return something to the javascript you have to echo it (string)
// if you want an array json encode it.

function pud_ajax_remember_setting() {

    // die if not page check (nonce) fails
    check_ajax_referer('ajax_nonce', 'nonce');

    // start session if not started
    if (session_status() == PHP_SESSION_NONE) {

    $_SESSION["page_clicked"] = $_POST['page_clicked'];
    echo $_POST['page_clicked'];


// Now everything is loaded at the right time:
// The javascript will receive 1 or two values
// - the path to the required admin-ajax.php full url
// - if a session value was set (above function) we want it

function remember_portfolio_filter()    {

    // first we create the array and put the admin-ajax.php in it
    // and the nonce a situation key that must be the same (website // php function)
    $value = array('ajax_url' => admin_url( 'admin-ajax.php' ),
                   'nonce' => wp_create_nonce('ajax_nonce')
    // if a session exists we put that in it
    // page_clicked should match some variabele names in the javascript file(4)
    if (isset($_SESSION["page_clicked"])) {
        $value['page_clicked'] = $_SESSION["page_clicked"];

    // we only load the script on a page
    if (is_page()) {
        // you can rename my-plugin filter but it has to be the same as in the rows below
        // you can rename the my-plugin.js but it should be the same as the file name 
        wp_register_script('my-plugin-filter', plugin_dir_url(__FILE__) . 'my-plugin.js', array('jquery'));
        // now we 'give'the $value (from above) to the javascript file
        wp_localize_script('my-plugin-filter', 'my_plugin', $value);
add_action('wp_enqueue_scripts', 'remember_portfolio_filter');

In the above the nonce is used, we have a post on that subject why nonce

Finish with the javascript file

The code below should go in my-plugin.js

 * with var my_plugin the my_plugin variabele exists
 * wordpress has put the array from wp_localize_script in it
var my_plugin;

// start one main function with some extra's
(function ($, root, undefined) {

    'use strict';

    // the ajax request function
    // page clicked should match the words in all lines with (4)
    function set_myplugin_page(page_clicked) {

            // we get my_plugin.ajax_url from php, ajax_url was the key the url the value
            url : my_plugin.ajax_url,
            type : 'post',
            data : {
                // remember_setting should match the last part of the hook (2) in the php file (4)
                action : 'remember_setting',
                nonce  : my_plugin.nonce,
                page_clicked : page_clicked
            // if successfull show the result in the console
            // you could append the outcome in the html of the 
            // page
            success : function( response ) {


     *      DOCUMENT READY

    jQuery(document).ready(function() {
        // when the page is loaded,  you can do anything you would like
        // this part can get a value from a clicked object
        // and runs the function with that value (page_clicked) 4
        jQuery("div").click(function( event ) {
            var page_clicked = ?????????????????????;

        // the next part checks if php has given the session value to java script file
        // and outputs to the console. You could open a tab that was previously used.
        if(typeof my_plugin.page_clicked !== "undefined")
            // uncomment to see the result in your console



})(jQuery, this);