This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I am passing two pieces of info to a php page using the $_GET method (team1, team2).
I'd like to use these as variables in some javascript. How can I do this?
Thanks
Since $_GET just access variables in the querystring, you can do the same from javascript if you wish:
<script>
var $_GET = populateGet();
function populateGet() {
var obj = {}, params = location.search.slice(1).split('&');
for(var i=0,len=params.length;i<len;i++) {
var keyVal = params[i].split('=');
obj[decodeURIComponent(keyVal[0])] = decodeURIComponent(keyVal[1]);
}
return obj;
}
</script>
Original answer:
In your .php file.
<script type="text/javascript">
var team1, team2;
team1 = <?php echo $_GET['team1']; ?>;
team1 = <?php echo $_GET['team1']; ?>;
</script>
Safer answer:
Didn't even think about XSS when I blasted this answer out. (Look at the comments!) Anything from the $_GET array should be escaped, otherwise a user can pretty much insert whatever JS they want into your page. So try something like this:
<script type="text/javascript">
var team1, team2;
team1 = <?php echo htmlencode(json_encode($_GET['team1'])); ?>;
team1 = <?php echo htmlencode(json_encode($_GET['team1'])); ?>;
</script>
From here http://www.bytetouch.com/blog/programming/protecting-php-scripts-from-cross-site-scripting-xss-attacks/.
More about XSS from Google http://code.google.com/p/doctype/wiki/ArticleXSSInJavaScript.
Cheers to the commenters.
Make sure you use something like htmlentities to escape the values so that your application is not susceptible to cross-site scripting attacks. Ideally you would validate the variables to make sure they're an expected value before outputting them to the page.
<script type="text/javascript">
var team1 = '<?php echo htmlentities($_GET['team1']); ?>';
var team2 = '<?php echo htmlentities($_GET['team2']); ?>';
</script>
<script type="text/javascript">
var team1 = <?php echo $_GET['team1'] ?>;
var team2 = <?php echo $_GET['team2'] ?>;
</script>
Another way to do this with javascript :
var team1 = $_GET('team1');
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
The other methods are kind of dirty, and there can be some problems. Your better off just using javascript:
<script>
function get_data(name){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null) return "";
else return results[1];
}
var var1 = get_data('var1');
var var2 = get_data('var2');
</script>
But this still isn't super secure.
Another way of doing this, which I just thought of, is to print the $_GET array. I don't know if that would work, though. Anyway, if it does, then here it is:
<script>
var _get = <?php print_r($_GET); ?>
var team1 = _get['team1'];
var team2 = _get['team2'];
</script>
And you would want to run array_walk(or something like that), on a function to clean each string.
Make sure your $_GET vars are available and not empty and use the following:
<script type="text/javascript">
var team1 = <?php echo $_GET['team1']; ?>;
var team2 = <?php echo $_GET['team2']; ?>;
</script>
Related
So, a quick breakdown.
I've got a function on my page loads three sections, currently it loads them separately (which is kind of slow). So I've recently combined them all.
I now have all of the information stored in PHP variables. I'd like to get those PHP variables and load them into separate divs.
here is an example of what I'd like to do.
HTML
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
PHP
$var1 = "<div><p>data 1</p></div>";
$var2 = "<div><p>data 2</p></div>";
$var3 = "<div><p>data 3</p></div>";
jQuery
//`get var1,var2,var3`
// load var1 into div.one
// load var2 into div.two
// load var3 into div.three
The current problem I'm having is json_encode is changing some information into this "\n\t\t\t\t\t\t" and it's printing
"<div><p>data 1</p></div>"
instead of "data 1" in a p inside of a div.
Try:
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<script>
var var1 = "<?php echo json_encode($var1); ?>";
var var2 = "<?php echo json_encode($var2); ?>";
var var3 = "<?php echo json_encode($var3); ?>";
$(".one").html(var1);
$(".two").html(var2);
$(".three").html(var3);
</script>
You can pass PHP to JS in this way, but not the other way around.
var var1 = "<?php echo json_encode($var1); ?>";
var var2 = "<?php echo json_encode($var2); ?>";
var var3 = "<?php echo json_encode($var3); ?>";
So I want to store all of my MySQL results in an array I can manipulate with javascript/jQuery.
Here is my current code:
<?php
$sql = "SELECT * FROM potentials";
$result = mysql_query($sql) or die(mysql_error());
$potential = mysql_fetch_array($result);
echo json_encode($potential);
?>
And my Javascript:
<script type="text/javascript">
$(document).ready(function(){
var myArray = "<?php print(json_encode($potential)); ?>";
console.log(myArray)
)};
</script>
I keep getting "Unexpected number" or "unexpected identifier". Whats going on?
json_encode() returns an object using JSON notation. Strangely, you surrounded it with quotes. Try removing them :
<script type="text/javascript">
$(document).ready(function(){
var myArray = <?php print(json_encode($potential)); ?>;
console.log(myArray);
});
</script>
(and it's not an array, it's an object, so you might want to rename your variable ;) )
You are using json_encode() twice, however if you want to use it, you need to parse it. In jQuery this can be done via jQuery.parseJSON like this
var myArray = jQuery.parseJSON('<?php print json_encode($potential); ?>');
Also if you want all the results, you need to loop the query (e.g. with while) and then save it to an array
$array = array();
while ($row = mysql_fetch_array( mysql_query( $query ) )
{
$array[] = $row;
}
<script>
var data = '<?php echo $data; ?>';
var json = JSON.parse(data);
console.log(json[0]); //etc
</script>
Notice that var data = ... is SINGLE QUOTED, so you catch the echo from php as a String
In php I used json_encode(...) and then got the value in Javascript, looks as the following:
["float","float","float","float"] // PS: This is a string...
And I would like to make this into a normal javascript array, like so:
Arr[0] // Will be float
Arr[1] // Will be float
Arr[2] // Will be float
Arr[3] // Will be float
How is this possible?
It sounds like you're retrieving a JSON string in JavaScript (perhaps via AJAX?). If you need to make this into an actual array value, you'd probably want to use JSON.parse().
var retrievedJSON = '["float","float","float","float"]'; // normally from AJAX
var myArray = JSON.parse(retrievedJSON);
If you're actually writing out a value into the page, rather than using AJAX, then you should be able to simply echo the output of json_encode directly, without quoting; JSON itself is valid JavaScript.
var myArray = <?php echo json_encode($myPhpArray); ?>;
var myArray = <?= json_encode($myPhpArray); ?>;
Pretty simple. ;-)
Example:
<?php
$myPhpArray = array('foo', 'bar', 'baz');
?>
<script type="text/javascript">
var myJsArray = <?= json_encode($myPhpArray); ?>;
</script>
Should output (view-source):
<script type="javascript">
var myJsArray = ["foo","bar","baz"];
</script>
Example
I reccomend using jquery. The php file should look as such ...
//location.php
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode($change);
?>
Then the jquery script ...
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>
<? foreach ($waiting_users as $waiting_user): ?>
<? echo $waiting_user->user_id; ?>
<? endforeach; ?>
I need to define the user id in a javascript variable. What is the best way of doing something like this?
<script type="text/javascript">
var user_id = "<? echo $waiting_user->user_id; ?>"; <-------------???
var post_id = "<? echo $post_id; ?>";
</script>
EDIT
The foreach returns just one user id. It's used to display a user that has signed up for a chat. Then I use the code below which is in end.js to delete the user from a table.
DELETE FROM table WHERE user_id = ? AND post_id = ?;
<a class="end" href="#" title="End">End</a>
$(document).ready(function() {
$("a.end").click(function() {
$.post(base_url + "index.php/home/end", { user_id : user_id, post_id : $(this).attr('id') }, function(data)
{
alert(data);
}, "json");
});
});
I would recommend getting the desired data through a service which you could call from javascript using ajax, but your version works too, although it is a bit messy.
If you really want to write php code that generates javascript code, I recommend you pass the whole object to the client side. Just make it a JSON and javascript will interpret it as a native javascript object.
<script type="text/javascript">
var users = <?php echo json_encode($waiting_user);?>;
// do whatever you want to do with the users
// ex : iterate over all users
for(var key in users)
{
var id = users[key].id;
// ...
}
</script>
UPDATE
If you only want to pass to the client side only the ids of the users, you should loop the users collection (in php) and store them in an array (or object). Then use the mechanism described above :
<?php
$user_ids = [];
foreach ($waiting_users as $waiting_user)
$user_ids[] = $waiting_user->user_id;
?>
// ....
<script type="text/javascript">
var user_ids = <?php echo json_encode($user_ids);?>;
</script>
Collect the user ids in an array and then output that array as JS.
<script type="text/javascript">
<?php
$user_ids = array();
foreach($waiting_users as $u) {
$user_ids[] = $u->user_id;
}
?>
var array_of_user_ids = <?=json_encode($user_ids)?>;
</script>
how can i get the id and key in this example script.
<script src=sample.jswidget?id=fhgfgd&key=yfgdghhdhdg type="text/javascript"/>
I guess you want to use your .js by writing :
<script type="text/javascript" src="Example.js?id=fhfhf&key=hfbhdvbh"></script">
Which is wrong.
Javascript uses global variables.
You can write :
<script type="text/javascript">
var id = "fhfhf";
var key = "hfbhdvbh";
</script>
<script type="text/javascript" src="Example.js"></script">
id and key will be known in your Example.js file.
This might work, but I haven't tested it
var scripts = document.getElementsByTagName("script");
if(scripts) {
var src = scripts[scripts.length-1].src;
src = src.match(/\?id=(.*)\&key=(.*)\&?/);
var params = {id: src[1], key: src[2]};
}
I used that on an extreme case that i needed the javascript to be different on every reload (not the values, some loops and the javascript was generated by a jsp page).
But i only used one parameter with a known name.
var query = window.location.search.substring(1);
var parms = query.split('RS=');
but I had a different page that i pulled in with jquery
I got it work now guys. I just change the
*example.js?*id=fhfhf&key=hfbhdvbh
adding the .js with .php extension
*example.js.php?*id=fhfhf&key=hfbhdvbh
And inside the example.js.php
<?php
var id = echo $_GET['id'];
var key = echo $_GET['id'];
?>