How to pass Javascript value to PHP in WordPress
Home » BLOG » WordPress » How to pass Javascript value to PHP in WordPress

How to pass Javascript value to PHP in WordPress

category:  WordPress

Sometimes, working on customization in WordPress we need to pass the PHP value to JavaScript or JavaScript value to PHP. Today I will share how to pass JavaScript value to PHP in WordPress.

Let says we have a criteria form in which the users can fetch the data by the criteria. The data will query from the database by PHP and display on the screen as it shows below. We actually take the example from one of my posts called “Building WordPress Plugins with Object-Oriented Concept“.

Example – Criteria form (screenshot)

Transactions page with criteria form

Add action hooks

In PHP, we will add the actions below.

// add the scripts and style on the backend ONLY
add_action( 'admin_enqueue_scripts', array( $this,'reports_admin_scripts') );  
add_action( 'wp_ajax_get_job_applications', array( $this, 'get_job_applications') );

Where to add the action hook

You can add the action hook in functions.php in your current theme. Or you can add the action hook in your main plugin file.

Create a function callback for script hook

Next, we will enqueue the style and scripts in our reports_admin_scripts function callback which we hook this function via admin_enqueue_scripts action.

Default scripts and JS libraries included and registered by WordPress core.

jQuery, Ajax and jQuery UI libraries are in WordPress core. So you don’t need to include these libraries into WordPress again.
You can check the default scripts and JS libraries included and registered by WordPress.

/**
  * add jquery ui datepicker widget
  * 
  */
public function reports_admin_scripts() 
{
  // add the script and style on our plugin only
  if (isset($_GET['page']) && $_GET['page'] === 'mct-reports') {

    // # load style
    // load datepicker plugin style
    // @link https://gist.github.com/miwahall/7028640
    wp_enqueue_style('mct-reports-bootstrap-style', MCT_REPORTS_PLUGIN_URL . 'css/datepicker-bootstrap3.css' );
    
    // load datatable plugin style
    wp_enqueue_style('mct-reports-datatable-style', MCT_REPORTS_PLUGIN_URL . 'lib/DataTables/datatables.min.css' );

    // load custom style
    wp_enqueue_style('mct-reports-style', MCT_REPORTS_PLUGIN_URL . 'css/mct-reports.css' );



    // # load scripts
    // datepicker plugin
    wp_enqueue_script( 'mct-reports-datepicker' , MCT_REPORTS_PLUGIN_URL . 'js/jquery-ui.min.js', array('jquery') ,true);
    wp_enqueue_script( 'mct-reports' , MCT_REPORTS_PLUGIN_URL . 'js/mct-reports.js', array('jquery','mct-reports-datepicker') ,true);
    wp_localize_script( 'mct-reports', 'mctReportsAjax', array(
        'ajaxurl' => admin_url('admin-ajax.php')
    ));
    // Important note: wp_localize_script() is a key function that we use for passing the JS values(JS values from the mct-reports.js) to PHP via ajax. In wp_localize_script function, you must use the same handle of attached script(mct-reports.js), in this case, it's 'mct-reports'. So WP can send the correct JS values. wp_localize_script() must be called AFTER the registered script using wp_register_script() or wp_enqueue_script(). Finally, you need to pass the ajax script from WP core. So that in your JS script, you can use ajax.

    // datatable plugin
    wp_enqueue_script( 'mct-reports-datatable' , MCT_REPORTS_PLUGIN_URL . 'lib/DataTables/datatables.min.js', array('jquery') ,true);
  }
}

Important Note

The wp_localize_script() is a key function that we use for passing the JS values (the values from the mct-reports.js) to PHP via ajax. In wp_localize_script function, you must use the same handle of attached script(mct-reports.js), in this case, it’s ‘mct-reports‘. So WP can send the correct JS values. wp_localize_script() must be called AFTER the registered script using wp_register_script() or wp_enqueue_script(). Finally, you need to pass the ajax script from WP core. So that in your JS script, you can use ajax.

Form submit from frontend and nonce

For a form submit from frontend, you should create the nonce for your form then check the nonce before using the submitted data. It is a security reason.

Here is an example
PHP code:
wp_localize_script( ‘mtm-script’, ‘mtm_ajaxobj’, array(
‘ajaxurl’ => admin_url(‘admin-ajax.php’),
‘ajaxnonce’ => wp_create_nonce(‘load_more_posts’))
);

JS code:
In ajax code, you will pass the ‘mtm_ajaxobj.ajaxnonce’ as data object along with action attribute you are passing. Below is an example.
data: {
action: ‘PHP_function_name’,
security: ‘mtm_ajaxobj.ajaxnonce’
}
The security label can be any name you want.

PHP code:
In PHP_function_name function, you can check the ajaxnonce with wp_verify_nonce function. Below is an example.
function PHP_function_name {
// Verify nonce
if (! wp_verify_nonce($_POST[‘ajaxnonce’], ‘load_more_posts’)) {
return false;
}
}

Create a function callback for ajax hook

Next, we will call the get_job_applications function via ajax. Remember, we hook the get_job_applications function with wp_ajax_get_job_applications action.

/**
  * get data from db
  */
public function get_job_applications() 
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'job_applications'; // do not forget about tables prefix
    $status = 'active';
    $orderby = 'date_created, firstname';
    $order = 'asc';

    // # the parameters from ajax are $_POST['start_date'] and $_POST['end_date']
    // set the query condition and convert date format for using in query
    $start_date = strtr( $_POST['start_date'], '/', '-' );
    $start_date = strtotime($start_date);
    $start_date = date('Y-m-d',$start_date);  

    $end_date = strtr( $_POST['end_date'], '/', '-' );
    $end_date = strtotime($end_date);
    $end_date = date('Y-m-d',$end_date);

    // get current user id
    $user_id = get_current_user_id();        
    
    // get user role
    $user_meta = get_userdata( $user_id );
    $user_roles = $user_meta->roles;

    // query data from the custom table
    $query_result = $wpdb->get_results(
      $wpdb->prepare("SELECT * FROM $table_name WHERE status = '$status' AND date_created BETWEEN '$start_date' AND '$end_date' ORDER BY %s %s", array( $orderby, $order ) )
      , OBJECT);
    
    
    // add post meta into the query result so we can use these values in ajax call
    foreach( $query_result  as $value ) {
        // get post meta
        $job_localtion_id = get_post_meta( $value->id_job_opp, 'job_location', true );
        $position_type_id = get_post_meta( $value->id_job_opp, 'job_type_position', true );
        $specialty_id = get_post_meta( $value->id_job_opp, 'job_specialty', true );    

        // get post title from custom post type
        $job_location = get_the_title( $job_localtion_id );

        // get term name by ID
        $position_type = get_term_by( 'id' , $position_type_id, 'job_types_position' )->name;
        $specialty = get_term_by( 'id' , $specialty_id, 'job_specialty' )->name;

        // add 3 additional columns for row grouping table
        $value->job_location = ( trim($job_location)==='' ? 'No Location' : $job_location );
        $value->position_type = ( trim($position_type)==='' ? 'No Position Type' : $position_type );
        $value->specialty = ( trim($specialty)==='' ? 'No Specialty' : $specialty );
    }

    // echo as json object to ajax calling
    echo json_encode($query_result);

    // # MUST add wp_die() here to avoid the 0 number that appends to the result json object and send back to ajax calling
    wp_die();
}

Always return as json and adding wp_die() at the end of function

For the PHP function that we will receive the JS values via ajax, if you want to return the value back to ajax, you must return the value as json. Of cause, in ajax, you must set dataType as json as well. At the end of PHP function, you must add wp_die() to avoid the 0 number that will appends to the result json object. Please try to use WordPress function( wp_die() ) instead of PHP function( die() ). So all hooks and filters will work properly.

Explanation for the criteria form action

  • After the user clicks on the report button at the criteria form, the click event is triggered.
  • In the JavaScript code, we will send the criteria values from the criteria form to the PHP function via ajax by the JavaScript code below. The JavaScript code is in mct-reports.js which we enqueue in reports_admin_scripts function callback.
jQuery(document).ready(function ($) {

  // ------- START Report button is triggered --------- //
  $('#btn_report').on('click', function (e) {

    // some JS code...

    // # getting db via PHP function
    // we pass the javascript values via data attribute. this way, get_job_application function(PHP function) can use these value. In PHP, you can access the javascript values by $_POST variable.
    // Note that: we use $_POST because in ajax, we use post method. If you use get method in ajax, in PHP, you will use $_GET to access the passing values.
    $.ajax({
      method: 'post',
      url: mctReportsAjax.ajaxurl,  // don't forget to pass ajax which we send by data object via wp_localize_script(). otherwise the ajax is not working.
      cache: false,
      dataType: 'json',  // we need the result back to ajax with json data type.
      data: {
        action: 'get_job_applications',  // we hook get_job_application function to wp_ajax_get_job_applications earlier.
        start_date: $txtStartDate.val().trim(),  // send JS value
        end_date: $txtEndDate.val().trim(),  // send JS value
      },
      beforeSend: function () {
        // some JS code...
      },
      success: function (response) {
         // display the result data from response variable into the screen
         // it will return the response as json which we set the dataType as json.
      },
      error: function (xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        console.log(err.Message);
      }
    });

  });
  // ------- END Report button is triggered --------- //

});
  • In the get_job_applications function(PHP code), we will query the data which is filtered by the criteria values.
  • We convert data to json for returning back to ajax.
  • At ajax, we will display the result data in the success function.

Full code

The code above is part of my tutorial. You can check the full code at “Building WordPress Plugins with Object Oriental Concept“.

Conclusion

Passing JS values to PHP, basically we send the values from the frontend to backend. It is not easy to do in normal PHP code. But with WordPress, it provides the wp_localize_script function which you can pass the JS values via ajax easily. In this tutorial, we use ajax at the backend only. So that we use the wp_ajax_{$action} hook. If you want to use ajax on the frontend for logged-out users, you will use wp_ajax_nopriv_{$action} hook. You can use both hooks if you want to use ajax on both frontend and backend.