How to pass multiple PHP variables to a jQuery function?

Posted by jcpeden on Stack Overflow See other posts from Stack Overflow or by jcpeden
Published on 2012-06-15T14:19:03Z Indexed on 2012/06/15 15:16 UTC
Read the original article Hit count: 138

Filed under:
|
|
|
|

I'm working on a Wordpress plugin. I need to pass plugin directories (that can change depending on an individual's installation) to a jquery function.

What is the best way of doing this? The version of the plugin that I can to work on had included all the javascript in the PHP file so the functions were parsed along with the rest of the content before being rendered in a browser.

I'm looking at AJAX but I think it might be more complicated than I need. I can get away with just two variables in this case (directories, nothing set by the user).

As I've read its good practice, I'm trying to keep the js and php separate. When the plugin initializes, it call the js file:

    //Wordpress calls the .js when the plugin loads
    wp_enqueue_script( 'wp-backitup-funtions', plugin_dir_url( __FILE__ ) . 'js/wp-backitup.js', array( 'jquery' ) );

Then I'm in the .js file and need to figure out how to generate the following variables:

    dir = '<?php echo content_url() ."/plugins"; ?>';
    dir = '<?php echo content_url() ."/themes"; ?>';
    dir = '<?php echo content_url() ."/uploads"; ?>';

And run the parse the following requests:

    xmlhttp.open("POST","<?php echo plugins_url() .'/wp-backitup/includes/wp-backitup-restore.php'); ?>",true);
    xmlhttp.open("POST","<?php echo plugins_url() .'/wp-backitup/includes/wp-backitup-start.php'); ?>",true);
    xmlhttp.open("POST","<?php echo plugins_url() .'/wp-backitup/wp-backitup-directory.php'); ?>",true);
    xmlhttp.open("POST","<?php echo plugins_url() .'/wp-backitup/wp-backitup-db.php'); ?>",true);
    window.location = "<?php echo plugins_url() .'/wp-backitup/backitup-project.zip'); ?>"; 
    xmlhttp.open("POST","<?php echo plugins_url() .'/wp-backitup/wp-backitup-delete.php'); ?>",true);

Content URL and Plugins URL differ only by /plugins/ so if I was hard pressed, I would only really need to make a single PHP request and then bring this into the JS.

© Stack Overflow or respective owner

Related posts about php

Related posts about jQuery