Reputation: 781
Can anyone tell me how to increment a php variable inside a javascript function.I have a javascript function which is called for every 3 seconds inside this function i need to increment the php variable.
<? php $k =0?>
function slide()
{
//increment $k
var j =<? php echo $k++; ?>//when I do this k is not incremented
}
Can anyone tell me where I went wrong?Is their any other alternative to do this?
Thanks,
Shruti
Upvotes: 2
Views: 7154
Reputation: 19
//You can do something like this:
<?php
$options= array('option1', 'option2','option3','option4');
?>
/* in the same file you can convert an array php into an array javascript with json_encode() php function*/
<script>
/*In this way you can read all the javascript array from php array*/
var options_javascript =<?php echo json_encode($options); ?>;
/*And you can increase javascript variables. For example:*/
for(var i =0; i<options_javascript.length; i++ ){
options_javascript[i];
}
</script>
Upvotes: 0
Reputation: 785856
You can return k from php and increment it in Javascript. Have your code like this:
<script>
<?php $k=5; echo "var k=$k;\n";?>
function slide()
{
//increment k
var j = k++; //k is incremented ONLY in javascript and j get's the k's value
}
</script>
Upvotes: 0
Reputation: 27852
Short answer: you don't.
Longer answer: PHP runs and only when the page is first loaded. This code is executed on the server. Javascript on the other hand is executed after the page has finished loading, inside the browser on the client's computer.
Maybe someone can give some advice if you tell us what exactly are you trying to accomplish.
Upvotes: 2
Reputation: 20475
PHP is run on the Server, Javascript is client side. What I think you want is a way to increment the JS value using Javascript not PHP.
The users never see php, so there is no incrementation happening.
You need to have a javascript function (clock) that keeps track of your 3 seconds, and then increase the value of your javascript var j
every elapsed period (if I understood your questions correctly).
Upvotes: 0
Reputation: 3330
You need to increment the variable before you print it:
<?php echo ++$k; ?>
Upvotes: 0
Reputation: 1183
PHP is serverside, Javascript is clientside. You can't mix apples and oranges and expect bananas. Two things work in a different way. Use JS if you need JS variable incremented.
Upvotes: 0