php variable together with javascript function - php

I have this piece of JS code:
<script type="text/javascript">
var counter = 0;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}
</script>
Which plusses a number with 1 everytime a button is pressed.
The variable "counter" decides what number to start with when the page is loaded.
This number is currently 0. But it is supposed to be a number from the database. So I made a database connection using PHP and I now have the database number in a PHP variable. However, how do I implement it on the JS script? I have tried this:
<script type="text/javascript">
var counter = $clicks;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}
The variable $clicks is the number from my database that is supposed to be the starting number when clicking the button.
I tried this as well, with no luck:
var counter = <?php $clicks ?>;

You're close. You're just forgetting to echo your variable's content:
var counter = <?php $clicks ?>;
should be:
var counter = <?php echo $clicks ?>;
or, if you have short tags enabled:
var counter = <?= $clicks ?>;

var counter = <?=$clicks?>;

Remember the echo.
var counter = <?php echo $clicks; ?>;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}

var counter = <?php echo $clicks; ?>;

Counter value should be assigned as
var counter = <?php echo $clicks ?>;

Related

In PHP, session variable is not storing the value. What is wrong?

The following is a sample PHP code. I am expecting the session variable 't' to increment its value when update function is called. However, when I run the code I keep getting the output as Value: 1. What should I do so that the value is stored into the session variable?
<?php
session_start();
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
function update() {
var ct = "<?php echo $_SESSION['t'] += 1 ?>";
<?php echo "Value: " . $_SESSION['t']; ?>;
$("#test").html(ct);
}
$(document).ready(function() {
setInterval('update()', 1000);
});
</script>
Put session_start() at the very top of your script, before any output
<?php
session_start();
// if you automatically set SESSION['t'] to 0 when the page loads, it will never increment
// check if the SESSION exists, and if it doesn't, then we create it
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<!-- it's recommended to load scripts at the end of the page -->
<script src="http://code.jquery.com/jquery.js"></script>
<script>
function update() {
// you had some formatting issues in here...
// shortcut: using +=1 will take the current value of $_SESSION['t'] and add 1
var ct = "<?php echo $_SESSION['t'] += 1 ?>";
<?php echo "Value: " . $_SESSION['t']; ?>;
$("#test").html(ct);
}
$(document).ready(function() {
setInterval('update()', 1000);
});
</script>
UPDATE:
This is an example that will do what I think you're looking for. It will display the value of $_SESSION['t'] when the page is loaded, and then increment the value of $_SESSION['t'] every time the update button is clicked. There is no error checking, this is just a very simple example to show you how this works.
<?php
session_start();
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<button type="button" id="update">Update</button>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function() {
// create the ct varaible
var ct = <?php echo $_SESSION['t']; ?>;
// display the value in the #test div
$("#test").text(ct);
// when the update button is clicked, we call ajax.php
$("#update").click(function(){
$.post("ajax.php", function(response){
// display the returned value from ajax.php
$("#test").text(response);
});
});
});
</script>
ajax.php
<?php
session_start();
// increment the session by 1
$_SESSION['t'] += 1;
// return the result
echo $_SESSION['t'];

SESSION variable with json array

i have an xml file in my server that i want to extract a list of IDs with php then convert the array to a JSON using json_encode() and put it in a $_SESSION variable, to make this clear my ideal JS function is:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = responseText;
});
}
//some other code
//return array; // this is an array i use later in js
}
in my getPL.php i have:
$videos_list = $theOne->parentNode->parentNode->getElementsByTagName('video');
for ($i = 0; $i < $videos_list->length; $i++) {
$a = $videos_list->item($i);
$id_out = $a->getElementsByTagName('id')->item(0)->nodeValue;
$array[$i] = $id_out;
}
$IDs = json_encode($array);
$_SESSION['IDs'] = $IDs;
echo $IDs;
break;
if i alert var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>; i get g8M8kxuaCWk,VWrBFt46J18
but when i alert the responseText i get ["g8M8kxuaCWk","VWrBFt46J18"]
all i want is to extract the IDs from the xml file and put them in a js array object
if there is anything need more tell me
i think you need the put quotes arround the php code in your JS like:
var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>';
ok i fixed it
so var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>'; would give me an array, which is what i actually want
but the alert(resposeText); was actually giving me a string so i did this JSON.parse(responseText);
thanks to who helped me get to this answer
after this in both cases if i alert(obj[0]); i get the first element so it is working
my ideal JS function becomes:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = JSON.parse(responseText); // this is the difference
});
}
return x;
}

how do I loop a php variable within a javascript script

I created a form with a text field that has Spry Validation (ie javascript). The user can select the number of rows in the form from 1 to 10. I need the code below to also expand but I'm not familiar enough with javascript to make it work.
$divkey is the variable that controls how many rows are in the form.
Original
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["change"], maxChars:20});
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
so I need the line 'var sprytextfield1...' to repeat based on $divkey with the next line being 'var sprytextfield2...' and so on. Can someone please rewrite this so it will work?
Trying to use php
<script type="text/javascript">
<?php for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Trying to use javascript
<script type="text/javascript">
var numwrestler = <?php echo $wrestlerkey; ?>;
var sprytextfield = [];
for (var i = 0; i < numwrestler; i++) {
var num = i+1;
var sprytextfield[num] = new Spry.Widget.ValidationTextField("sprytextfield"+num, "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
I'd recommend that you use a Javascript array for this type of task.
Your code is mostly correct, but the var in your for loop is incorrect, and the creation of the num variable instead of just using i is redundant.
<script type="text/javascript">
var sprytextfield = new Array();
var numwrestler = <?php echo $wrestlerkey; ?>;
for(var i = 0; i < numwrestler; i++){
sprytextfield[i] = new Spry.Widget.ValidationTextField("sprytextfield"+(i+1), "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Be sure that your PHP variable(s) are defined in the file before you include them in your script.
In your PHP code, you never define the variable divkey, by deafault the value will be 0.
Try:
<script type="text/javascript">
<?php $divkey = 10; for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Please, note that the variable that you are using as index $num in every iteration of the loop will be increasing 2, because of the i++ and the $num=$i+1

how to solve this setTime out in javascript with an if condition?

here's my script , it's a combined php and javascript
<?php
$countdown = strtotime("22:00") - time();
$itemtime = "22:00";
$realtime = substr(date('H:i'),0,5);
?>
<script>
var itemtime = "$itemtime";
var countdown = '$countdown';
var url = "$redirectpage";
var realtime = "$realtime";
// HOW WILL I ADD AN IF STATEMENT WITH THE SETTIMEOUT FUNCTION
// WHEREBY, if(realtime == itemtime) ..that's the only time the
// redirection should occur
setTimeout(function(){
location.href='$redirectpage';
},countdown * 1000);
</script>
<?php
$countdown = strtotime("22:00") - time();
$itemtime = "22:00";
$realtime = substr(date('H:i'),0,5);
?>
<script>
var itemtime = "<?php echo $itemtime;?>";
var countdown = '<?php echo $countdown;?>';
var url = "$redirectpage";
var realtime = "<?php echo $realtime;?>";
// HOW WILL I ADD AN IF STATEMENT WITH THE SETTIMEOUT FUNCTION
// WHEREBY, if(realtime == itemtime) ..that's the only time the
// redirection should occur
setTimeout(function(){
if(realtime == itemtime) location.href='$redirectpage';
},countdown * 1000);
</script>
Assuming $redirectpage is set in JavaScript and not PHP. If it is set in PHP, you'll need to assign it as I did above.
I ended up with my own solution,i place this inside the setTimeout function
if(countdown < 0) setTimeout("location.reload(true);",1000); location.href= "$redirectpage";

How do I retrieve values from a PHP array?

I have a array stored in a PHP file in which I am storing all the values.
I am trying to loop through the entire array in JavaScript. How should I do that?
The following does not work:
var index = 0;
var info = 1;
while(index<4) {
info = <?php echo $a[?>index<?php];?>
index++;
}
You can copy array from php to JavaScript and then process it.
var array = <?php echo json_encode($a); ?>
var index = 0;
var info = 1;
while(index<4) {
info = array[index];
index++;
}
I don't know what version of php you're using, but try something like this:
var info = null;
var a = <?php echo json_encode($a); ?>;
for(var index=0;index<a.length;index++) {
info = a[index];
}
You need to process the PHP into Javascript first. You can use json_encode to do this.
var index = 0;
var info = 1;
var a = <?php echo json_encode($a); ?>;
while(index < 4) {
info = a[index];
index++;
}
PHP runs on the server side, before the final page is served to the client.
Javascript runs on the client side (on the browser).
Therefore, what you are trying to achieve won't work. What you can do is use PHP to print the javascript code dynamically.

Categories