Pass value from php to javascript - 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

Related

Call variable from another script in HTML

I currently have a HTML file that has one script that is declared as follows:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
code.......
var a = "hello"
});
</script>
I am trying to add another script within the HTML file that will call on this variable "a". Right now, I am doing something like this:
<script type="text/javascript">
alert(a);
</script>
But it is not alerting anything. If I replace a with a string like "hello", I do get alerted. Am I calling the variable wrong? I've tried searching for solutions but all of them say you should be able to easily call variables from another script assuming that script is declared and initialized before. Thanks.
Move the a declaration outside of the function.
E.g.,
var a;
$(document).ready(function() {
code.......
a = "hello"
});
And then later on...
alert(a);
Remember that variables are function-scoped, so if you define it inside of a function, it won't be visible outside of the function.
Update based on comments:
Because you now have a timing issue when trying to interact with the a variable, I would recommend introducing an event-bus (or some other mechanism) to coordinate on timing. Given that you're already using jQuery, you can create a simple bus as follows:
var bus = $({});
bus.on('some-event', function() {});
bus.trigger('some-event', ...);
This actually lends itself to some better code organization, too, since now you really only need the bus to be global, and you can pass data around in events, rather than a bunch of other random variables.
E.g.,
var bus = $({});
$(document).ready(function() {
var a = 'hello';
bus.trigger('some-event', { a: a });
});
And then in your other file:
bus.on('some-event', function(e, data) {
alert(data.a);
});
JSBin example (obviously not spread across multiple files, but the same principles apply).
Replace your code as
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
var a="";
$(document).ready(function() {
a = "hello";
});
</script>
Now you can access the variable a as below.
<script type="text/javascript">
alert(a);
</script>
The problem with your code was that, you was declaring the variable a inside $(document).ready() which made it local to the ready().
When you write a inside function block you make it a local variable, you can move variable declaration outside of the function block as other answer say or you can use:
$(document).ready(function() {
window.a = "hello";
});
and later:
alert(a);
In both cases you are declaring a as a global variable and that is not recommended.

Why doesn't this function modify the global version of the array?

I have defined a variable in what I think is global scope. I want to modify the same variable inside a function that lives in a class, then use it later to export as json data.
The function is called by the xataface api, so I'm not sure I can mess with the function signature to do something like passing by reference. I've thought I might access the instance of this action class in the javascript embedded php, but I don't know how to ask the api for it, nor am I confident of its lifetime. It seems like a global variable may be the way to go. In any case, I want to know:
Why is not the global instance of $dataset1 the one being modified inside the function?
Why doesn't the call to array_push put anything on either array?
<?php
//non-dynamic data delcared in global scope. This is picked up later
//in a php block embedded into javascript
$dataset1 = array(array("label"=>"c120","data"=>"1"),
array("label"=>"c150","data"=>"10"),
array("label"=>"camp","data"=>"7"));
class actions_time_in_type
{
function handle(&$params)
{
$this->app =& Dataface_Application::getInstance();
//The Query
$result = mysql_query("SELECT typeDes, total
FROM myTable", $this->app->db());
//reserch leads me to believe that this *should* make all subsequent
//references to $dataset1 use the global instance
global $dataset1;
//experimenting with appending more non-dynamic data
//for some reason, this syntax does not seem to touch $dataset1
array_push($dataset1, array("label"=>"dv20","data"=>"1"));
//This syntax is working, but $dataset1 is not the same as the global
//$dataset1. Prepending "global" here seems to crash the script
$dataset1[] = array("label"=>"pa18","data"=>"5");
while($row = mysql_fetch_assoc($result))
{
//append data to the array, again, this is not hitting
//the global instance of $dataset1
$dataset1[] = array("label"=>$row['typedes'],"data"=>$row['total']);
}
mysql_free_result($result); //Frees the result after finished using it
//diagnostic dump to see what we've got
//This shows that we've constructed the dynamic data set, but it
//seems to be scoped only to this function and does not make it into
//javascript.
var_dump($dataset1);
}
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
<script type="text/javascript">
$(function () {
//This is getting only what was done original init of $dataset1, nothing that
//happened in the function made a difference
var dataset1 = <?php echo json_encode($dataset1); ?>;
});
</script>
It appears this is indeed a problem with execution order. Since the manipulation of the data happens within a class definition which in turn is called by the api, there appears to be no assurance that the global definition of the data will be in scope when it is time to manipulate the data, or that it will have been manipulated when the data is re-used further down.
For the interested reader, I was able to get the api developer to demonstrate the proper way of integrating javascript with the api calling the in-class function:
https://groups.google.com/forum/#!topic/xataface/l6qBzxF1vrc

jquery pass value into function AFTER function?

I am new to javascript & jQuery. I'm trying to create a feature for my site that let's people display badges they have earned on their own site (and I would supply a bit of code they could just copy/paste). I had someone help me with the javascript and I have it working perfectly, but I can't find any jQuery documents that explains it to me?
<script type="text/javascript">
(function(id) {
// include js via php file with the id in as a parameter
})("myid");
</script>
The id is passed in the area labeled "myid", in jQuery can you pass in a static variable this way? When I try to delete ("myid") and change it to var id = 'myid', the function no longer works.
The occurrence of "myid" in the code you are showing is not a static variable. It is a string literal that is being passed as an argument to an anonymous function. The anonymous function is declared and then is immediately getting called.
If you are wondering why the programmer wrote the JavaScript the way they did. The following might help.
Both of the examples below will display "myid" in an alert:
Example 1:
<script type="text/javascript">
var id = 'myid';
alert(id);
</script>
Example 2:
<script type="text/javascript">
(function(id) {
alert(id);
})('myid');
</script>
The first example declares "id" as a variable. It is a global variable and is actually added as a property to the window object. The second example defines an anonymous function and immediately calls it, passing in 'myid' as the value of the "id" parameter. This technique avoids using a global variable.
Of course, you could also avoid the global variable by doing the following:
<script type="text/javascript">
(function() {
var id = 'myid';
alert(id);
})();
</script>
If you stick "myid" in a variable and then pass in that variable, it'll work. Like this:
var memberID = "myid";
(function(id) {
// include js via php file with the id in as a parameter
})(memberID);
If you say this...
(function(id) {
// include js via php file with the id in as a parameter
})(var id = 'myid');
...you're attempting to stick a variable declaration in a function call, which won't work. That's why declaring the variable above and apart from the function call won't throw any errors.

How to path files in 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');
}

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.

Categories