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

How to pass Javascript value to PHP in WordPress

posted in: WordPress

Working on customization in WordPress sometimes 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 sample from one of my posts here.

Criteria form

In PHP, we will add the actions below.

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

We will enqueue the style and scripts in reports_admin_scripts function.

/**
  * 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')
    ));

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

We will call the get_job_applications function via ajax.

/**
  * 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();
}

Explanation

  • After the user clicks on the query button, the click event is triggered
  • In the Javascript code, we will send the criteria value to the PHP function via ajax as the Javascript code below
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 value to data attribute. this way, get_job_application function(PHP) can use these value. In PHP, you can access the value by $_POST.
    $.ajax({
      method: 'post',
      url: mctReportsAjax.ajaxurl,
      cache: false,
      dataType: 'json',
      data: {
        action: 'get_job_applications',
        start_date: $txtStartDate.val().trim(),
        end_date: $txtEndDate.val().trim(),
      },
      beforeSend: function () {
        // some JS code...
      },
      success: function (response) {
         // display the result data from response variable into the screen
      },
      error: function (xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        alert(err.Message);
      }
    });

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

});
  • In the get_job_applications function, we will query data filtered by the criteria value
  • Then we will display the result data in the success function in ajax