Trying to run php code within a Javascript (.js) file - php

First off I am very new to php so bear with me. I have a javascript (.js) file from a wordpress template that reads the key from var googledockey. In order to change it I have to manually open the .js file and change that variable. What I would like to do is have the .js file grab the key from where it was saved on a page I made. Here is the code for the admin page that has the textfield for me to enter in a key.
<?php
if($_POST['gdocs2wp_hidden'] == 'Y') {
//Form data sent
$gdkey = $_POST['gdocs2wp_gdkey'];
update_option('gdocs2wp_gdkey', $gdkey);
?>
<div class="updated"><p><strong><?php _e('Options saved.' ); ?></strong></p></div>
<?php
} else {
//Normal page display
$gdkey = get_option('gdocs2wp_gdkey');
}
?>
The key saves and whenver I open the page they key shows up so I know this half is working. This is where I am stumped. Within my .js file which is in a subdirectory of the admin page, the var googledockey is where I have had to manually save the key which works everytime. I have tried <?php echo $gdkey; ?> and get_option('gdocs2wp_gdkey'); to try and get the key but I havent had any luck. Can php work within a .js file? Does anyone have any insight to help me along? Thanks
var jqueryNoConflict = jQuery;
//var googledockey = <?php echo $gdkey; ?>
var googledockey = "INSERTmyKEYhere";
// begin main function
jqueryNoConflict(document).ready(function(){
initializeTabletopObject(googledockey);
});

You could always have the JS run an Ajax call to get the data. Alternatively, you could move the variable declaration to the PHP/HTML file where you include the JS, and just add
<script type='text/javascript'>
var googledockey="<?echo $gdkey;?>"
</script>

1. Register your script
Create a JavaScript file, place it in your theme folder, and register it with WordPress.
wp_register_script(
'google-docs',
get_bloginfo('template_directory') . '/scripts/google-docs.js'
);
Documentation: http://codex.wordpress.org/Function_Reference/wp_register_script
2. Enqueue your script
Whenever your script is needed in a template, you enqueue the file.
wp_enqueue_script(
'google-docs'
);
Documentation: http://codex.wordpress.org/Function_Reference/wp_enqueue_script
3. Localize your script
This allows you to make PHP variables available in your JavaScript.
wp_localize_script(
'google-docs',
'google_docs_vars',
array(
'key' => $google_doc_key
)
);
Documentation: http://codex.wordpress.org/Function_Reference/wp_localize_script
4. Use variable in your script
Now you have access to the variable in your script.
var google_docs_key = google_docs_vars.key;
That's it. I think this would solve your problem and it's also the proper way to do it.

JS files are not generally parsed for PHP. The easiest (albeit not the prettiest) way to do this is probably to either:
1) Echo the value in a hidden DOM element in the page template itself, and then use JS to grab that element and set the variable (so, put the value inside a hidden element on the page, or as an attribute or something, then grab that value using JS and assign it to your variable).
2) Similar to above, just put the variable declaration in an inline script (<script>code</script>) because that WILL get parsed for PHP - see Seriyia's answer.
3) Use simple AJAX calls which are really easy with jQuery and let you pass data from JS to a PHP function somewhere else like functions.php and then back to the JS. This might be more trouble than it's worth though if you aren't familiar with AJAX.

This is quite simple
You are recently using this code snipet
var jqueryNoConflict = jQuery;
//var googledockey = <?php echo $gdkey; ?>
var googledockey = "INSERTmyKEYhere";
// begin main function
jqueryNoConflict(document).ready(function(){
initializeTabletopObject(googledockey);
});
Where you need to Replace this with following code
var jqueryNoConflict = jQuery;
var googledockey = "<?php echo $gdkey; ?>"
var googledockey = "INSERTmyKEYhere";
// begin main function
jqueryNoConflict(document).ready(function(){
initializeTabletopObject(googledockey);
});

Related

Wordpress Admin - Function not defined?

I'm having problems trying to call a Javascript function from an enqueued javascript file used whilst editing Wordpress pages. I have created a simple meta box with some AJAX hyperlinks that I want to be able to call functions from the Javascript file (pretty simply stuff but I keep getting error "blah(1) is not defined".
HTML CONTAINED IN METABOX:
Delete Item
JS:
function blah(theid){
if ( confirm("Are you sure you wish to remove this image (Note: Images are not removed from the Media Library)?") ) {
var data = {
action: 'myajax-delete',
imgid: theid
};
jQuery.post(ajaxurl, data, function(response) {
//Parse the JSON Object
var object = jQuery.parseJSON(response);
if ( response.status == 'true' )
{
jQuery('#file_' + theid + '_row').remove(); //remove TR
alert('Image removed from this portfolio');
}else{
alert('Sorry, that image could not removed right now, please reload the page and try again.');
}
});
Note: The PHP server side code works fine and responds absolutely as expected to my manual Posts. The javascript file is definitely present and being downloaded by the browser as expected.
If I use the following line of code below, the AJAX works (so I know the JS is OK) but I need to be able to call the function by name rather use a selector. I'm very keen to work out why I can't call a simple function!!!!
jQuery('.delete_pimg').click(function() { ^Above code^ }
Just to re-cap the error I get when the link is clicked: 'blah(1) is not defined'
I hope I've explained this clearly - if not, please give me a shout :)
Ok Basically - I could not get this to work. My javascript is absolutely fine, so In order to call my own functions, I declared them within the page itself rather than calling in a JS file. This seems to work and my code executed with no errors straight away.
I.e
<script type="text/javascript">function blah(id){alert("This Works Nicely!");}</script>
A work around but at least solved my problem anyway.
Wipes sweat from forehead
I was having the same issue where blah() is not defined, and found out I needed to have the enqueued js file just define the function, instead of wrapped with a jQuery(document).ready(function($) { function blah(param){[...]} }).
Here's what my code looks like now, which got everything working for me:
Inside of functions.php
(short snippet within my file)
function blah_init() {
# Want this on all pages
# Queue JS and CSS
wp_enqueue_script(
'blah-file', // handle
get_template_directory_uri() . '/assets/js/blah-file.js', // source
array('jquery'), // registered script handles this script depends on
'1.0', // version
true // true = in footer, false (or blank) = in <head>
);
}
add_action('wp_enqueue_scripts', 'blah_init');
Inside of blah-file.js
(this is the full contents of the file)
//jQuery(document).ready(function($) {
function blah(param) {
console.log('Blah triggered: ', param);
}
//})
Inside of header.php and footer.php
(short snippet where I output some link, such as social link)
<!-- Ignore the href, this has nothing to do with getting this to work -->
Facebook

Pass URL into JS function

I have a PHP page with where I also use jQuery UI functionality. User drags Item from left panel into a box on the right. After it is dropped a dialog appears. If user clicks the first button he/she is redirected to a URL. I need to be able to change URL based on a user.
I can get the URL into a var or $_SESSION but I can't figure out how do I change it inside my JS function?
Here's the DEMO (drop item into box to get dialog).
UPDATE:
Below are all valid suggestions, however, my problem is that I have most of JS functions in external JS file (dragdrop-client.js).
I have added new var to my main PHP file
var endURL = "http://google.com";
but how do make my function checkLaunchpad() use it?
There are a number of different ways to do it, but often it is as simple as:
<script type="text/javascript">var myURL = '<?php echo $url; ?>'</script>
Where $url is the url you want them to go to (perhaps '/boxes.php?uid='.$_SESSION['id'];?)
That will translate to:
<script type="text/javascript">var myURL = 'http://whatever.and.stuff'</script>
EDIT
You just asked how you would have a function declared on an external JS page use the variable.
Well, fortunately, JS doesn't care when you declare the variable, so long as it has some value before you use it. And, if it doesn't have a value then, it will supply undefined;. This means you can declare functions which rely on global variables which won't exist for another three or for seconds/minutes/years/eons/whatever.
Additionally, the earlier a script tag is on a page, the earlier it will be evaluated -- a variable declared in the first tag will exist when the second js file loads.
So, if you want to have the above work as expected you have two options.
You could define the variable as the first script tag in the body of the page (thus, it is defined before checkLaunchpad is.
<script type="text/javascript">var myURL = '<?php echo $url; ?>'</script>
<script type="text/javascript" src="path/to/js"></script>
Or, if checkLaunchpad isn't called until after the body has loaded, you can place the definition anywhere in a script tag!
Find below code to redirect users to new page
<script type="text/javascript">
var endURL = "http://google.com";
function checkLaunchpad(url) {
location.href=url;
return false;
}
</script>
Test
for more reference check http://snook.ca/archives/javascript/global_variable
I would say store the url in a hidden field like:
<input id="hidUrl" type="hidden" value="<?php echo $url ?>"/>
And then change your javascript so it uses the value:
window.location = $("#hidUrl").val();

Get config data to javascript file - magento

I have a really simple requirement but cant find a good solution to it.
How do I get config data into javascript files within magento. I need to load some config data from a module and make it available from within some javascript code. Without loading this data onto hidden fields on the page or using ajax to fetch them from a controller - how do i do this?
Thank you in advance for any help.
You can grab the value you are looking for like this:
// using seo as an example. look at the path field on core_config_data
$value = Mage::getStoreConfig("web/seo/use_rewrites");
Put this in a template that will echo your code:
<?php
$seo_value = Mage::getStoreConfig("web/seo/use_rewrites");
?>
<script type='text/javascript'>
magento_config = {}
magento_config['seo_value'] = "<?php print $seo_value; ?>";
// ... add more ...
</script>
Add that template to your layout and you will now have a global JS object called magento_config that you can use to grab your values. Depending on where you put your template, you may have to wait for the page to load before your variables are available.
Make sure not to echo these values indiscriminately, as there may be security implications in echoing store config data to the frontend.
Hope that helps!
Thanks,
Joe
Add this code in before you load the JS...
<script type="text/javascript">var var_name = <?php echo $var_name; ?></script>
Then you can load in JS like
<script type="text/javascript" src="/js/file.js"></script>
In your file.js (providing that the file is loaded after the variable definition) you can do something like...
//execute as soon as DOM is loaded
window.onDomReady(onReady);
//do on ready
function onReady()
{
alert(var_name);
}
Or if you were using jQuery
$(document).ready(function(){ alert(var_name); }

php tags in .js file

How do I enter a <? echo "hello"; ?> in a .js file.
This is a jquery app, therefore the js file.
Thanks
Jean
You would only be able to do this if the PHP interpreter is configured to run on *.js files, which by default it won't be. Quite honestly, I wouldn't recommend this behavior.
What I'd do instead is something like this (This method can be used for CSS files, too.):
<script type="text/javascript" src="js.php"></script>
js.php
<?php
//GZIP the file and set the JavaScript header
ob_start("ob_gzhandler");
header("Content-type: text/javascript");
//Set a JavaScript variable based on PHP work
echo 'var logged_in_user = "'.$_SESSION['username'].'";';
//Require an external script
require_once($_SERVER['DOCUMENT_ROOT']."/path/to/jquery.js");
?>
//More Javascript functions and code here
$(document).ready(function() {
$('#mydiv').tipsy();
});
<?php
//Flush the output buffer
ob_end_flush();
?>
I personally do this for many reason.
I have many jQuery files I want to include, but I don't want my browser doing 5+ HTTP requests. Including them all in one file means less HTTP requests.
GZIP! I'm significantly reducing the size of the file be transferred and that speeds things up for the visitor.
It's a central location to add, remove, or modify my JavaScript for the whole site. I can even use $_GET checks to make certain scripts conditional based on how I wrote the <script> tag.
For example, <script type="text/javascript" src="js.php?var=1"></script>. I can then check $_GET['var'] within the js.php file.
You regularly don't use PHP within your JavaScript files. Javascript is a client-side language which is interpreterred in your web browser. PHP is run on the web server.
However, if you need to pass data from your PHP-code to your javascript document, you can do something like:
$js = "<script> myObject = " . json_encode($your_data) . " </script>";
print $js;
If you do this in your <head>-part of your HTML-document, you will have access to myObject in other JS files you load after that.
$your_data can be an array or any kind of object, string or integer. Look for PHP JSON around the interwebs.
I think is not possible to enter a php in the js file, but:
try to create an element div for example or an input ...
and then use this functions to get the value of the div tag.
function AddHiddenValue(oForm) {
var strValue = document.getElementById("city").value;
alert("value: " + strValue);
var oHidden = document.createElement("input");
oHidden.name = "printthisinput";
oHidden.value = strValue;
oForm.appendChild(oHidden);
}
It come from another object form (select .. )
document.getElementById("city").value;
Ok guys here is the answer
The Q: I want to input a value for a variable into a .js file, php tags are not permitted and the js would throw an error.
The A: write a
<script> <? var value_pass = echo "hello"; ?> </script> before the said .js file
In the said .js file
var value=value_pass;
So there is no need to have any of the ob_end_flush.
If this is not viable please let me know.
Thanks
Jean

Include Jquery script in .js page

Sorry if title is not too clear but I think it's about right. NEhow, what I would like to do is a bit like (well is to a certain extent) building a widget with JQuery (pref), PHP & CSS.
What I would really like to happen is for a "member" of my site to simply paste 2 lines of code in their HTML to load the widget. Something like this:
<script type="text/javascript" src="http://www.mydomain.com/script.js"></script>
Then to display the widget something like this <div id="displaywidget"></div>
OK that bit is "easy" and ok. But how do I include JQuery or "something" to generate the widget in script.js
What I mean is "displaywidget" - the ID of the widget div will be the name of a php file on my server so essentially script.js will need to load displaywidget.php into the div displaywidget.
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
Thinking as I write "pure" java can do "most of what I want i.e. document.getElementById('displaywidget'), BUT I would prefer to also "include" Jquery.js as I would like some aspects of the widget to use JQuery. Example being the JQuery UI date function.
Sorry if I am rambling a bit but trying to think as I go along. My "real" problem is I am not too sure on "pure" javascript i.e. getting the div to display/load displaywidget.php
Suggestions please. (Oh if I am barking up the wrong tree please feel free to tell me - nicely:) )
Thanks in advance
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
You're looking for the AJAX behaviors inside of jQuery which would make the call to the php page and then push the data into the div.
You should be loading jQuery early on in the process, right up front in your head element. Once its loaded it will be cached so no worries of its on every page. No real overhead incurred.
Once jQuery is installed you can call one of many AJAX functions related to obtaining data and popluation elements. Theres $.load(), $.ajax(), and a few others that escape me unless I go and check out their docs section.
You can do all of this without jQuery, but its more code and you have to control for browser differences.
You can load jquery into script.js, just copy and paste it after or before whatever javascript lives in script.js.
So if script.js is:
//start of file
alert('ex');
//end of file
Make it:
//start of file
alert('ex')
Copy and pasted Jquery source
//end of file
After a bit more "trawling & thought" I found this code:
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
script_tag.onload = scriptLoadHandler;
script_tag.onreadystatechange = function () { // Same thing but for IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonp_url = "http://al.smeuh.org/cgi-bin/webwidget_tutorial.py?callback=?";
$.getJSON(jsonp_url, function(data) {
$('#example-widget-container').html("This data comes from another server: " + data.html);
});
});
}
})(); // We call our anonymous function immediately
writtend by Alex Marandon and found here http://alexmarandon.com/articles/web_widget_jquery/ - works a treat, exactly what I wanted, including/installing JQuery into a .js file

Categories