Modifying PHP Session Variables with JavaScript - javascript

I have some implicit PHP functions which are to be called on particular front-end events; such as button onclicks. By doing so this should modify my PHP SESSION variable accordingly. However, both functions, setAlan() and setMark(), seem to be getting called even if I just want the first one to execute.
<?php
session_start();
function setAlan() {
$_SESSION['passed_user']='alan';
}
function setMark() {
$_SESSION['passed_user']='mark';
}
?>
<script>
function getAlan() { $(document.body).append('<?php setAlan(); ?>'); }
function getMark() { $(document.body).append('<?php setMark(); ?>'); }
function show() { alert(' <?php echo "{$_SESSION['passed_user']}" ?> '); }
</script>
<div class="pod">
<div class="pod_title"><h2>Select a User</h2></div>
<div>
<input type="button" onclick="getAlan();" value="alan">
<input type="button" onclick="getMark();" value="mark">
<input type="button" onclick="show();" value="show">
</div>
</div>
I don't understand why setMark() is being called automatically? By what I've written, I believe I am only defining the PHP functions, not calling them; I use JS for that. Am I missing something? Thanks in advance!

PHP is executed first, server side. Once PHP is done, your browser ( client ) gets the result, Javascript is executed on the client, so after PHP is done.
You can't mix javascript and PHP as you did with:
<script>
function getAlan() { $(document.body).append('<?php setAlan(); ?>'); }
function getMark() { $(document.body).append('<?php setMark(); ?>'); }
function show() { alert(' <?php echo "{$_SESSION['passed_user']}" ?> '); }
</script>
However you can use Javascript to call some server side PHP script with ajax ( Asynchronous JavaScript and XML ).
http://www.w3schools.com/ajax/default.ASP

Related

PHP: echo as condition of if statament?

I need to put echo as condition of if statement. So, for example:
<html>
...
...
<body>
<form onsubmit"<?php $c=false; if(echo "<script>example();</script>";){ $c=true; } echo "\""; if($c){ echo "action=\"./\"";} method="post">
...
</form>
...
...
<script>
function example()
{
alert("This is only an example");
if(..) return true;
return false;
}
</script>
</body>
</html>
So I need to create a function in JavaScript (this top is only an example, but, in realty, it is more complicated) and call it in the if statement.
Update
The code should be execute "action" of the form only if the Javascript function is true.
PHP runs in the server. JavaScript runs in the client. So php can't use a js variable or its function to server side action. What u can do is , u can call JS function from PHP like
echo "<script> myFunction() </script>";
But in the same same case, u can use php values for JS actions,
eg
<script>
var x = <?php echo $myVar ?>
if(x == true){
alert("yahooo");
}
</script>

PHP statements inside javascript external file

I need to do javascript action depends on $_SESSION php status:
if(isset($_SESSION['logged']) && $_SESSION['logged'] == true)
{
echo <<<END
$("#I-like-it").click(function()
{
$(this).css({"font-size": "20px" });
});
$("#I-dont-like-it").click(function()
{
$(this).css({"font-size": "20px" });
});
END;
}
else
{
echo 'alert("You must be logged in to vote!")';
}
This is external js file. How am I supposed to use PHP statements in this JS file?
My code doesnt work :c
PHP runs on the server, Javacript run on the browser. You can pass information from PHP to Javascript, and you can pass information to the server FROM JavaScript. But they cannot execute at the same time.
What I suggest doing is to use Javascript to read your PHP variable while it loads
<script>
var serverSession = <? echo $_SESSION['logged'] ?>
</script>
Then your JavaScript can do whatever it needs to with that.
No, It can't, this is different type file, PHP is server side and JS is client side, but you can write javascript at your php file like this one :
<?php
if(isset($_SESSION['logged']) && $_SESSION['logged'] == true)
{
echo '
<script>
$("#I-like-it").click(function(){
$(this).css({"font-size": "20px" });
});
$("#I-dont-like-it").click(function(){
$(this).css({"font-size": "20px" });
});
</script>
';
}
else
{
echo '<script>alert("You must be logged in to vote!")</script>';
}

How to call included php file with AJAX?

I am not sure if this is best approach, but how to make AJAX call with included file? Let me make working simple example.
I have, main index.php file, with following content, where I want to access all data returned from included file where magic happens. Data is array type in reality.
<?php
require_once('magic.php');
?>
<html>
<body>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="POST">
<input type="text" name="variable" id="variable" />
<input type="submit" value="Do magic" name="submit" />
</form>
<?php
echo "<pre>";
print_r($data);
echo "</pre>";
?>
</body>
</html>
And "magic.php" file, where all the magic happens.
<?php
$variable = $_POST['variable'];
function doMagic($variable) {
# do some magic with passed variable ...
# and return data
return $data;
}
$data = doMagic($variable);
# now return $data variable so main file can use it
return $data;
?>
What I want to do is to call this function doMagic() with AJAX, but all logic is already included and available in global space, and return $data to modal or pop-up window.
What is best approach, because I am already passing variable to included file?
Use ajax like the following
$('form').submit(function(){
$.ajax({url: "magic.php",
data: {variable : $'#variable').val()},
success:function(data){console.log(data);});
});
and in magic.php, use json_encode
<?php
$variable = $_POST['variable'];
function doMagic($variable) {
# do some magic with passed variable ...
# and return data
return $data;
}
$data = doMagic($variable);
# now return $data variable so main file can use it
return json_encode($data);
?>
Since you have jQuery as a tag...
You could do something like this:
In your index.php:
<input type="text" id="variable">
<div id="#myButton"></div>
<div id="#response"></div>
Then have a Javascript file (or include in your index.php):
$('#myButton').click(function(){
var myVariable = $('#variable').val();
$.post( "magic.php",{variable: myVariable}, function(data) {
$( "#response" ).html( data );
});
});
This basically means, when you click the item that has the id of myButton, it'll grab the value of what's inside of the input with the id of variable, POST that via jQuery.post() to your magic.php file, and return the data. Then, it replaces the html of the div with the id of response with the data it returns.
Just make sure to include the jQuery library

How to execute js(scrollLeft) from php?

i have a function to scroll a div like this:
function scrTo(id, to)
{
document.getElementById(id).scrollLeft = to;
}
and try to call it via php:
echo"<div id='movingtab' style='overflow-x:auto; width:765;'>";
echo"<table>...Some Table Content...</table>";
echo"</div>";
if(isset($_GET['scrl']))
{
echo"<script type='text/javascript'>";
echo"scrTo('movingtab', '".$_GET['scrl']."');";
echo"</script>";
}
The idea is to scroll to last position after the content of div changed via ajax, but when the script executed the scroll is back to begining and not back to last scroll position before div content loaded. I've try to call the function via <script onload="">, but still not working. Can anyone help solve my problem?
Probably Should use:
echo "<script type='text/javascript'>
$(document).ready(function() {
scrTo('movingtab', '".$_GET['scrl']."');
});
</script>";
<?php if(isset($_GET['scrl'])) { ?>
<script type='text/javascript'>
function scrTo(id, to){
document.getElementById(id).scrollLeft = to;
}
</script>
<?php } ?>
<div id='movingtab' style='overflow:auto; width:765px; border:1px solid blue;'>
<table><tr><td>...Some Table Content...</td></tr></table>
</div>
<button id="scroll" onclick="scrTo('movingtab', '<?php echo $_GET['scrl']; ?>')">scrollLeft()</button>
Your approach is wrong. You should call the function in the callback of your ajax request. This functionality should be done solely in JavaScript. If you are echoing JavaScript from PHP it is most probably the wrong approach.

passing value to javascript to php variable: It do not work?

In this program similar_text function do not work but echo successfully print $var_1 and $var_2. What is the exact error?
<script>
var j=prompt('1st name','Name')
var l=prompt('2nd name','Name')
</script>
<?php
$var_1 = '<script>document.write(j)</script>';
$var_2 = '<script>document.write(l)</script>';
similar_text($var_1, $var_2, $percent);
echo $var_1, $var_2;
echo $percent;
?>
PHP is executed first, on the server, then it gets served and then only javascript is executed on the client-side. so the variables you are using in php part are not set at that moment.
If you need to interact with a php script from javascript, you odd to use an ajax request.
you need close php and open again
<script>
var j=prompt('1st name','Name')
var l=prompt('2nd name','Name')
</script>
<?php
$var_1 = '<script>document.write(?>j<?php)</script>';
$var_2 = '<script>document.write(?>l<?php)</script>';
similar_text($var_1, $var_2, $percent);
echo $var_1, $var_2;
echo $percent;
?>
or same.

Categories