SHARE
TWEET

jQuery + Vars

JasmineVismitananda Nov 15th, 2017 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Index
  2. <div id="id"></div>
  3.  
  4. // Script.JS
  5.  
  6. /*
  7.  *   How to use that thing.
  8.  */
  9. jQuery(document).ready(function(){
  10.     jQuery.ajax({
  11.         url: php_vars.adminajax,
  12.         data:{action:"mycred_dejatuwow_point"},
  13.         success:function(e){
  14.             jQuery("#id").html(e);
  15.         }
  16.     });
  17. });
  18.  
  19.  
  20. //functions.php
  21. <?php
  22. function enqueueWP(){
  23.     /*
  24.      * Enqueuing a script that require jQuery working, not need to link jQuery CDN as before.
  25.      */
  26.     wp_enqueue_script(
  27.         'script',
  28.         get_template_directory_uri() .'/js/script.js',
  29.         array('jquery'), // This load hosted jQuery script
  30.         null,
  31.         true
  32.     );
  33.  
  34.     /*
  35.      * Create a Javascript Variable used by script.js
  36.      */
  37.     $datas = array(
  38.         'adminajax' => admin_url( 'admin-ajax.php' ), /* Create the array */
  39.     );
  40.     wp_localize_script(
  41.         'script', // HANDLE: Where the var must be used
  42.         'php_vars', // Name of the array
  43.         $datas // Var Passed
  44.     );
  45. }
  46. add_action('wp_enqueue_scripts','enqueueWP');
  47.  
  48. /*
  49.  * Passing this var to result in script.js
  50.  */
  51. function mycred_dejatuwow_point() {
  52.     echo "USER ID: ".get_current_user_id()."<br>";
  53. }
  54. add_action( 'wp_ajax_mycred_dejatuwow_point', 'mycred_dejatuwow_point');    // If called from admin panel
  55. add_action( 'wp_ajax_nopriv_mycred_dejatuwow_point', 'mycred_dejatuwow_point');
RAW Paste Data
Top