简体   繁体   中英

Load php file with jquery wordpress

I implemented in my worpdress theme ios button switch and when someone click the button the script load a php file with the text: on or off

Here is the code:

  <script type="text/javascript">

$('#1').iphoneSwitch("<?php echo get_user_meta( $current_user->ID, '_fbpost_status', true); ?>", 
 function() {
   $('#ajax').load('<?php bloginfo( 'template_url' ); ?>/includes/ajaxswitch/on.php');
  },
  function() {
   $('#ajax').load('<?php bloginfo( 'template_url' ); ?>/includes/ajaxswitch/off.php');
  },
  {
    switch_on_container_path: '<?php bloginfo( 'template_url' ); ?>/includes/ajaxswitch/iphone_switch_container_off.png'
  });

So on.php have only the "Activated" text and of.php "Stoped" text. The on and off files have not included the wordpress variables. How can I include them? To make a update in db. Or do you know any better method for doing the update?

Since you're using WordPress, the propper way of doing this is to send a JavaScript variable with wp_localize_script in functions.php :

add_action('wp_enqueue_scripts', 'my_frontend_data');
function my_frontend_data()
{
  global $current_user;
  wp_localize_script('data', 'Data', array(
    'userMeta' => get_user_meta($current_user->ID, '_fbpost_status', true),
    'templateUrl' => get_template_directory_uri()
  ));
}

The above will add a JavaScript Data variable that's accessible in all your pages. Then you can use it in the front-end like so:

var ajaxUrl = Data.templateUrl +'/includes/ajaxswitch/';

$('#1').iphoneSwitch(Data.userMeta, function() {
  $('#ajax').load(ajaxUrl +'on.php');
}, function() {
  $('#ajax').load(ajaxUrl +'off.php');
}, {
  switch_on_container_path: Data.templateUrl +'iphone_switch_container_off.png';
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM