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); }
Related
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);
});
I have something like this:
LOL
<script type="text/javascript">
$('#lol').click(function(){
$.get("<?php echo $host.'/index.php'?>",
{ page: "topobjekt", index: "<?php echo $l;?>", pages: "<?php echo $pg+1;?>" },
function(data){
$('#primary_content').html(data);
});
});
Is it possible to load specific div(for instance #secondary_content) from my GET requested php page and load it into #primary_content target?
Why not modify your PHP script to handle the AJAX request specifically? You will save wasted bandwidth loading a whole page when you know all you need is one div.
Add a get variable and check for this to determine context.
Change this line:
$('#primary_content').html(data);
To this:
$('#primary_content').html(data.find("#secondary_content"));
You can also use the load method, which can specify elements in the target page:
$('#primary_content').load('<?php echo $host.'/index.php'?> #secondary_content');
You should be able to do something like
$('#primary_content').html(data.find('#theDivId'));
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();
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
I'm trying to create a module in joomla, which uses one jquery plugin. I've to do an ajax operation while clicking on an element in the module. Currently I'm specifying the whole path to the php file. But I know Its a wrong method.
The code in jquery plugin is like this.(please note the second line where the path is specified in the jquery plugin file)
$.get(
"/subdirectory/MyBlog/modules/mod_calendar/getCalendar.php", {
month: $("#selectedMonth").val(),
year: $("#selectedYear").val(),
flag: '-1'
}, function(data){
$("#monthlyCalendar").html(data);
$("#monthlyCalendar").show();
}
);
What is the correct method to specify the path in a jquery plugin file.
Also I need to know where to put my jquery plugin file in the module.
I found an answer in the following blog.
http://blog.subooa.com/development/joomla-coding/ajax-in-joomla-with-jquery/
The best way I found to do it is to use the JURI::root method to create a javascript variable that I can then use. In your php code, you would do something like this:
?>
<script type="text/javascript">
var joomlaRoot = '<?php echo JURI::root(); ?>';
</script>
<?php
You can then use that variable when you are doing your AJAX call.
As for where to put the jquery plugin file in your module, you can put it whereever you want under your module's directory and then use JURI::root again to create a path to it and call the JDocument::addScript method.
On a side note, you may consider using MooTools. It comes bundled in Joomla! already. It has the ability to do AJAX calls. Also, by using it, you avoid the possibility of having jQuery conflicts.
Atlast I was able to find a good solution to use the Ajax using Jquery in Joomla.
For this first you need to create a view and model to get required html through AJAX call.
Then use jQuery code similar to the following to get only the output of the required view.
//Code to get the base URL of joomla installation
szURL = document.URL;
componentList = szURL.split('/');
szDocument = componentList[componentList.length-1];
szURL = szURL.replace(szDocument, "");
//URL to the required component
url = szURL + "?option=COMPONENT_NAME&view=VIEW_NAME&tmpl=component&uid=" + getRandomValue();
jQuery.get(url, function(data) {
jQuery("#mydiv").html(data);
});
//Function to get a random number
//It is used for Ajax calls from IE; Else IE will use the cache values
function getRandomValue(){
return Math.floor(1000000 * (Math.random() % 1))
}
Note the URL used for the ajax call. It uses "tmpl=component" to get only the html for the selected component without joomla HTMLs.