increment php variable in javascript function - php

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

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.

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).

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.

You need to increment the variable before you print it:
<?php echo ++$k; ?>

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>

//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>

Related

HTML marquee change behaviour

If I put marquee in while loop it shows all the data at the same time, sliding right to left. I want this to behave one by one, when one finishes the second starts... and lastly the first comes again, how can I do this please help me out I would be very grateful to you, thanks in advance :)
$data=mysql_query("SELECT heading from moto_static_pages");
while($res = mysql_fetch_assoc($data)){
echo '<marquee behavior="scroll" direction="left" style="padding:0 0 10px 0;">';
echo $res['heading'];
echo '</marquee>';
}
PHP is server-side. Everything is computed on the server, and then all at the same time displayed on the browser in-front of you. So your loop is merely looping around what eventually will be displayed in the browser, and printing it all out at once, which is what it's supposed to do.
You will need to use JavaScript to accomplish this, as this is client-side. You cannot do this with PHP.
You will need to retrieve all the data from your database, convert it to json (json_encode()), and send this to your browser as one string. Then, in JavaScript, loop through the json and print out each one as a marquee with a timed event.
To reiterate, unless you are going to be doing something with asynchronous I/O with PHP, which you aren't, you will need to do this with JavaScript.
This is untested code and straight from the top of my head, but hopefully this will point you in the right direction.
<?php
// Server-side code, get your data, json encode it too!
$data = json_encode(mysql_query("SELECT heading from moto_static_pages"));
?>
<script type = "text/javascript">
// Client side code that happens in real time in the browser
// Get your data from your php variable
var data = JSON.parse(<?php echo $data; ?>);
// Loop your data
for (var i = 0; i < data.length; i++)
{
// Output your data in marquees
setTimeout(function() {
document.write("<marquee behaviour='scroll' direction='left'>");
document.write(data[i].heading);
document.write("</marquee>");
}, 4000); // Every 4 seconds
}
</script>
Don't expect this code to just work for you, so get debugging it and using var_dump() to see what you get from PHP, and console.log() to see what you have in JavaScript.
Final Note
mysql_query has been deprecated and should be used with caution. You should check out PDO / mysqli instead; they're not too hard to understand and they're interesting too!

Using $.post to send JS variables to PHP script

I am trying to send Javascript variables over to a PHP script for updating scores of a quiz game. I've looked up the shorthand method of doing this, which is $.post, but I am unable to retrieve the values in the PHP script. I am fairly unfamiliar which JS and require help as to what I am doing wrong.
Here is the Javascript
function updatescore(){
var thisgamemarks= 2300;
var thequizid = 5;
$.post("updatemark.php", { quizidvalue: thequizid, newmarkvalue: thisgamemarks } );
}
And the PHP
$studentnewmark = $POST['newmarkvalue'];
$thisquizid = $POST['quizidvalue'];
$thisstudentid = $_SESSION['studentid'];
type $_POST instead of $POST. also, on a windows based machine, you can use ctrl + shift + j to debug a js script - which will help if if there's any problems with your code. but, the js code you have shown us looks perfectly fine.
Yes. As suggest use the $_POST instead of $POST and try putting the "quizidvalue" in the javascript inside quotations. It might help. Just a thought. It's how I always do it.

using for loop value from javascript with php variable

I have this code that executes a for loop in javascript with a php array inside of it. Is there anyway I can use the variable for the loop inside of the php variable for example. This is all inside of php.
echo '<script>
for (var i =0; i<4;i++){
alert("hey"'.$phparr[i].');
}</script>';
I know this will not work because the $phparr is a php variable while the i is a javascript variable is there anyway I can do this?
Try:
<script>
var phparr = <?php echo json_encode($phparr); ?>;
for (i in phparr){
alert("hey" + phparr[i]);
}
</script>
PHP is a server side language which means it executes before it reaches the client (browser).
JavaScript is a client side language which means it is executed in the browser (client side).
The best tool for a new web developer is Google search.
Learn how to search effectively.
You're almost there. In order to access the php array in javascript, you first have to echo out the php array into a javascript array. Try:
$phparr_imploded = implode(',',$phparr);
echo '
<script>
var arr = ['.$phparr_imploded.'];
for (var i =0; i<4;i++){
alert("hey"+arr[i]);
}
</script>
';
If your php array is coming from a database, or contains special characters that javascript may misinterpret, make sure to sanitize before outputting.
Are the objects in your php array strings? If so, you need to surround the objects with escaped quotations BEFORE the implode.
for($i=0; i<count($phparr); $i++){
$phparr[i] = '"'.$phparr[i].'"';
};
How about storing the PHP array in a Javascript variable and looping through as kpotehin suggests?
<script>
var i = 0, name;
var myArr = <?php echo json_encode($my_array); ?>;
while (name = myArr[i++]){
alert("hey " + name);
}
</script>
You should make it this way:
var arr = ["<?php echo implode('","',$array); ?>"];
for (var i =0; i<4;i++){
alert("hey"+ arr[i]);
}
Your basic problem is that you are forgetting that the PHP code and the JavaScript code do not execute at the same time. The PHP runs to completion, outputing HTML and JavaScript. Then the browser runs the JavaScript. If the JavaScript needs dynamic access to data in a PHP variable (including an array), then the PHP needs to generate JavaScript declaring the data in a JavaScript structure. That is what all the other answers are doing.

How to combine PHP and Javascript together?

I have a function in my Javascript script that needs to talk with the PHP to get the data in my database. But I'm having a small problem because I start the PHP in the for loop in Javascript, and then inside that for loop I get the data in my database. But the pointer in the for loop inside the PHP code is not working.. I guess the problem is in escaping? Or maybe it's not possible at all.
Here's my code:
(function() {
var data = [];
for(var i = 0; i < 25; i++) {
data[i] = {
data1: "<a href='<?= $latest[?>i<?=]->file; ?>'><?= $latest[?>i<?=]->title; ?></a>", // The problems
data2: ....
};
};
});
I think you are confused, you are trying to use a variable of javascript in php.
You cannot do this:
<?= $latest[?>i<?=]->file; ?>'
Which expands to:
<?php
$latest[
?>
i
<?php
]->file;
?>
how can you possibly know the value of i, if i is a variable generated in the client side?, do not mix the ideas, i is defined in the browser and the php code is on the server.
You may want to consider using PHP to output the JavaScript file, that way the PHP variables will be available wherever you want them.
The following links better explain this.
http://www.givegoodweb.com/post/71/javascript-php
http://www.dynamicdrive.com/forums/showthread.php?t=21617
1.Pass the javascript variable to the URL to another php page.
window.open("<yourPhpScript>.php?jsvariable="+yourJSVariable);
2.Then you can use this variable using $_GET in the php script.
$jsVaribleInPhp=$GET['jsvariable'];
//do some operation
$yourPhpResult;
3.Perform any server side operation in the Php and pass this result.
header("Location:<your starting page>?result=".$yourPhpResult);
4.Redirect back to the page you started from thus passing the result of PHP.
Php and Javascript have different roles in web development.
This task can also be performed if there's a php script and js in the same page. But that I leave for the readers to work it out.
Hope this helps!!

Passing jquery variable to php

I have the following jquery code:
while (count < 31) {
window['cday_' + count] = <?php echo $day_1 ?>;
window['tday_' + count] = (window['cday_' + count] * formfig) / formfig2;
count++;
}
But I need $day_1 in the php echo statement to reflect the variable "count", so in theory it should be something like "echo $day_count". Is it possible to pass the var to php?
php & jquery coding:
$i=0;
while ($i < $num) {
${"day_$i"}=mysql_result($result,$i,"datavalue");
$i++;
}
?>
<script type="text/javascript">
var chart1;
var count=1;
var formfig=17;
var formfig2=2;
function chartdraw(){
while (count < 31) {
window['cday_' + count] = <?php echo $day_1 ?>;
window['tday_' + count] = (window['cday_' + count] * formfig) / formfig2;
count++;
}
The short answer here is no.
To understand what's possible, you need a deep understanding of what's going on. Your PHP code is building an HTML document (with embedded JavaScript) and sending it on to the web browser. Once the web browser (which is, of course, running on the user's machine, not your server) renders that page, it will execute the javascript. This is when the javascript variables begin to actually mean something. Until then, they are just text getting sent across the network. This point is long after the PHP code has finished running. Your server has already closed down that php instance as it sent the code to the user.
Keeping that in mind, you can send the value of a javascript variable (or any number of other things) back to your server with something called an ajax request. Essentially, this will send some information (the variable's value, and the name of the page you want) back to your server, which will in turn cause your server to build a new web page, which can have PHP code in it. That web page's content will get returned to another bit of javascript you can provide -- called a 'callback' -- which can take the page created by the second php script and make use of it. This is, of course, fairly resource intensive.
Unless you plan to do something that ONLY PHP can do, I would recommend finding a way to do as much of your logic as possible in javascript. This alleviates all these complex problems and keeps all the hard work on the user's machine.
If you can structure your code so your php code provides all the data the javascript code needs before the php finishes running, you can get away without doing anything fancy with ajax. Here's an example:
<script type="text/javascript">
var days = {};
<? for($day = 0; $day < 30; $day++) { ?>
days.<? echo $day ?> = "<? echo get_day_info($day) ?>";
<? } ?>
</script>
What this will do is create a javascript object called days. Then it will fill in days.i for i from 0 to 30. It assumes you have a function called get_day_info($day) which takes a day and returns the info for that day. I'm assuming here that you're dealing with strings -- if not, you will need to remove the quotes, and possibly do other things to wrap the data depending on what format it takes.
I belive the only way is using ajax. http://api.jquery.com/jQuery.ajax/
Not without changing your approach significantly.
The problem is that PHP exists entirely on your server, where javascript exists in the browser. PHP does really know anything about javascript. PHP will completely render your page before any javascript has been run at all. So there is no way to get this value back in easily.
You can use ajax in order to run javascript which can load data or hit URLs on your server, but you cant simply substitute javascript variables in PHP. The reason you can do it with PHP variables is because the PHP actually is generating the javascript.
Have javascript store the value in a hidden field and pick up the value with PHP that way?

Categories