How to path files in javascript? - javascript

I've this code in a fille called: general.js
if($('#showcase').length) {
$.include('js/jquery.aw-showcase.js');
}
But as we all know, Wordpress uses bloginfo('template_url') to path files.
In front-end not work because show incorrect path <script type="text-javascript" src="js/jquery.aw-showcase.js"></script>
How to solve it?

Maybe not the best solution, but you could always declare a JS variable early in your main index file, like such:
<script type="text/javascript">
var template_url = "<?php bloginfo('template_url') ?>";
</script>
Now, in your general.js file, you can reference it as such:
if ($('#showcase').length) {
$.include(template_url + '/js/jquery.aw-showcase.js');
}
You should usually avoid using a global variable, but it might be the only solution in this case.
EDIT: You might actually want to use wp_localize_script instead of declaring a global variable.

At least, could you not try this ?
if($('#showcase').length) {
$.include('/wp-content/themes/yourthemename/js/jquery.aw-showcase.js');
}

Related

Passing a value from a javascript to another js file

My code is...
<script type="text/javascript">
function changeval() {
$total = parseInt($("#small").val()) + parseInt($("#medium").val());
}
</script>
How can I pass '$total' to another js file, say main.js.
Call changeval function from another file, save/use returned value.
function changeval() {
return parseInt($("#small").val()) + parseInt($("#medium").val());
}
Or have one global variable save value inside the same variable and access it from another file.
Make sure that $total is assigned to the global scope and make sure the script where you want to use it is below the script where you assign it. Be careful about polluting the global scope too much because it can make code that is very tricky to debug and can cause strange errors if you overwrite a native global variable.

Pass value from php to javascript

Hello Im trying to pass value stored in php to javascript code.
I try to pass the value in $_SESSION[user]
If I have this script in my header:
<script>
var user = ? //How to pass the value?
</script>
In my buttons I do something like this:
onclick="foo('<?php session_start(); echo $_SESSION[user];?>')
But how do I pass it without the user click?
Thanks for helping
EDIT
My JS function located in other file and I reference them by this code in my header:
<script src="class_functions"></script>
How do I pass the same parameter to the other file?
Just echo the PHP value out like you would any content:
<script>
var user = '<?php echo $_SESSION[user]; ?>';
</script>
JavaScript is just client-side code like HTML is.
If you're PHP script is rendering the page, I would go with the script tag approach.
<head>
<script type="text/javascript">
var user = '<?php echo $_SESSION["user"]; ?>';
</script>
</head>
<body>
</body>
Now that you have added an additional factor to your question, it is a little bit more interesting. If you need to set a variable when the functions that use this variable are located in a different file, then you need to decide the scope of the variable you are passing. There are several options; I will just list two:
Global scope. That is, the variable will be "known" to the other functions because of where it it located. You want to be careful of this, but if that's your approach you can use any of the answers given, e.g.
<script>
var x = '<?= $_SESSION["user"];>';
</script>
Local scope. Now you will need to include a function in class_functions that sets the variable. You might end up with something like
<script>
set_user('<?= $_SESSION["user"];>');
</script>
Where the set_user() function is defined in your other file, and ensures that the variable is available to the other functions with the correct scope.
I would prefer using method 2 - it is much cleaner.
I think this is better:
<script>
var user = '<?php echo htmlentities($_SESSION["user"]); ?>';
</script>
Because if there are quotes $_SESSION['user'], you will get an error.
For example if you have:
$_SESSION['user'] = "something with 'quotes'";
the js would like so:
var user = 'something with 'quotes'';
Which is incorrect.
You Can use Jquery ,if you want it to happen automatically.
just Use the following code inside your tags
$(document).ready(function()
{
var user= <? echo $_SESSION['user']?>;
//Code Goes here......
});
Hope that solves Your Problem
Note:This can be one of the many possible solutions

Mixing registerScript (with PHP variables) with registerPackage in Yii

I'm developing a Web Application using Yii Framework. I started by hardcoding javascript and css files (even though it might not be the best pratice, I use this method in another application).
I'm trying to achieve something like this:
<html><head>
....
(css includes)
<script type="text/javascript" src="http://www.myapp.com/js/vendor/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
if (typeof(myapp) == "undefined") { var myapp = {}; }
var myapp = {
ui : {},
var: {}
};
myapp.var = {
baseurl: '<?php Yii::app()->getBaseUrl()'
};
});
</script>
<script type="text/javascript" src="http://www.myapp.com/js/myapp.dialog.js"></script>
<script type="text/javascript" src="http://www.myapp.com/js/myapp.customjqgrid.js"></script>
So, I created two packages in config/main.php:
package 'jquery' that includes jquery (first script)
package 'commonjs' that includes my common files (myapp.dialog.js and myapp.customjqgrid.js)
However, both myapp.dialog.js and myapp.customjagrid.js use the variable "myapp.var.baseurl". So, the order of the includes must be:
package jquery
inline jquery
package commonjs.
My PHP in layout is something like this:
<?php
Yii::app()->clientScript->registerPackage('jquery');
Yii::app()->clientScript->registerScript('helpers', "
if (typeof(myapp) == 'undefined') { var myapp = {}; }
var myapp = {
ui : {},
var: {}
};
myapp.var = {
baseurl = '".Yii::app()->getBaseUrl()."/'
};
", CClientScript::POS_READY);
Yii::app()->clientScript->registerPackage('commonjs');
?>
The problem is that I can't define a position of registerScript relative to registerPackage or define a dependency between registerScript and registerPackage.
I know it is possible to define dependencies between packages, but then how could I pass my PHP variables to JS ?
Is there an easy way to do this or is it better to continue to include JS and CSS manually?
Thank you.
Yes, packages are not suited for such usage.
You either work as it is: register package then register base url script
or
create widget, with sole purpose to include your scripts and generate JS variables in one single file. That way you would replace your "registerPackage" with "widget" method and you will get same result.

oo javascript with properties from server, methods from cache, best practice?

I'm converting procedural JS to OO and would appreciate any help.
In a nutshell, what I have is a html-page containing:
<script type="text/javascript">
var serverTime='11:32:20'; //time generated by server (php)
</script>
<script scr="myProcFuncs.js" type="text/javascript">
/* which is containing procedural functions such as
function getServerTime() {return window.serverTime;}
*/
</script>
What I like to do is a clean up, without increasing traffic, more or less...
<script type="text/javascript">
function myOb() {
this.serverTime = '11:32:20';
this.serverDate = '2010-09-24';
}
//first question, need/recommended to create a class??
var myCl = myOb();
</script>
<script scr="myMethods.js" type="text/javascript">
//second question, how to append methods to initiated class or object?
</script>
What I'm asking for is not only what works, but best practice in the OO-JS. Please also concider delayed loading of external myMethods.js and so on...
Options I'm concidering are:
§1, as example, add methods to initiated class (or static object if possible), and if so, please post example of appending method.
§2 (worst case) use two objects, one for properties (server generated), and one for the methods.
Thankful for any light in this matter, all the best
//Tom Joad
function myOb() {
this.serverTime = '11:32:20';
This doesn't work. this only has meaning in a function if it's being called as a method on an object, or with the new operator.
If you just do myOb() instead of new myOb(), then this will be the global (window) object and assigning this.serverTime is effectively creating global variables, what you were trying to avoid in the first place. (Also without a return value from the function, myCl will be undefined.)
Since you don't really seem to be doing anything that requires multiple instances or prototyping, forget the function and just use an object literal:
var pageValues= {
serverTime: '11:32:20',
serverDate: '2010-09-24'
};
you can easily generate code like this using a JSON encoder on the server side. For example if the server-side language you're using were PHP:
<?php
$pageValues= array('serverTime'=>'11:32:20', 'serverDate'=>'2010-09-24');
?>
<script type="text/javascript">
var pageValues= <?php echo json_encode($pageValues); ?>;
</script>
how to append methods to initiated class or object?
Use an inline function expression:
pageValues.someMethod= function() {
...do something...
};
However I'm not sure this really gets you anything. JavaScript is a mixed scripting language, you don't have to think like Java and try to force everything into objects and classes. (Especially since you don't actually get classes, and have to roll your own using prototyping.)
Solved for now with, (and fixed some typos...):
<script type="text/javascript">
function myCl() {
this.serverTime = '11:32:20';
this.serverDate = '2010-09-24';
}
var myOb = new myCl();
</script>
<script scr="myMethods.js" type="text/javascript">
/* myMethods.js containing methods as..
myOb.getTime = function() {
return this.serverTime;
}
*/
</script>
Works. If anyone knows a better way, please post.

How can I get my JavaScript, referencing a var defined externally, to validate?

I have an HTML file with a couple of external JavaScript files. Here's an example, somewhat simplified from the real HTML and JavaScript files:
<head>
<title>Control Page</title>
<script language="JavaScript" src="control.js"></script>
<script language="JavaScript">
var myWindow;
var controlForm;
function onPageLoad() {
myWindow = document.getElementById('iframe1');
controlForm = document.getElementById('ControlForm');
}
</script>
</head>
<body onLoad="onPageLoad()">
....
</body>
</html>
and then in my JavaScript file control.js:
function messageArrival(message) {
chatwindow.contentWindow.document.write(message)
}
function makeNetMeetingCall() {
controlForm.Status.value = ....
}
....
My question: When I validate the external JavaScript file, it complains about the variables that are defined in the main HTML file because they aren't declared anywhere in the *.js file. For example, MyEclipse's JavaScript editor complains that it sees variables used that are not defined in any visible scope. How can I declare these variables in the JavaScript file so that it's clear the variables are expected to be defined externally, something similar to "extern" in C.
This sounds more like an issue with MyEclipse's JS editor than your JS.
Unfortunately, I'm not familiar with MyEclipse. However, I do know of a good JS validator, JSLint, which accounts for global variables by having you define them in the comments:
/*global getElementByAttribute, breakCycles, hanoi */
You could declare the variables in the global scope of your control.js file.
var controlForm;
function makeNetMeetingCall() {
// ...
}
this won't interfere with the code that finally defines these objects, as it executes first. But even if it didn't, without an initializer it wouldn't overwrite anything.
If you need proof about the overwriting, just did this in the JS shell:
$ js
js> var x = 1;
js> print( x );
1
js> var x;
js> print( x );
1
js>
In reality, the problem is that your "IDE" isn't aware of them. It hasn't connected the HTML page JS variables with the external javascript file. One way around this, is to put the variable declaration into the external javascript file.
You need to declare the variables before the controls.js script is included:
<script language="JavaScript">
var myWindow;
var controlForm;
function onPageLoad() {
myWindow = document.getElementById('iframe1');
controlForm = document.getElementById('ControlForm');
}
</script>
<script language="JavaScript" src="control.js"></script>
That should stop eclipse from complaining, but the execution will be the same.

Categories