PHP statements inside javascript external file - javascript

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>';
}

Related

Access javascript variables on server php file via browser javascript

using javascript code in browser to access javascript variable in server php file
( the php file search a text file and returned result as a php variable, then I set that php variable as javascript variable)
//php file on server called data.php
<?php
$search = 'bing';
// Read from file
$lines = file('text.txt');
$linea='';
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false) {
$liner=explode(': ',$line);
$linea.= $liner[1];
}
}
echo 'Search returned: '. $linea;
<script type=\"text/javascript\">
var varxxx = $linea;
</script>
?>
//text file on server
foo: bar
el: macho
bing: bong
cake color: blue berry
mayo: ello
//Java script code in browser.
var xhr = new XMLHttpRequest();
xhr.open("GET","http://.........data.php",false);
xhr.send(null);
$Variables.setValue(5, 'varxxx');
I got
reference error
x is not defined
if I just run http://.........data.php , it shows Search returned:"Bong"
it means data.php successfully returned the result, and php $linea is Bong.
so this part below in the php file is what causes the error?
<script type=\"text/javascript\">
var varxxx = $linea;
</script>
or something wrong with my Javascript code in browser?
Any help is appreciated
Thanks in advance
Try "echoing" the script tag to the .html body.
You're getting this error because the variable is being created on the server side only, thats why the variable is not defined. Also I recomend you to use let instead of var, let is more secure in terms of scope.
//php file on server called data.php
<?php
$search = 'bing';
// Read from file
$lines = file('text.txt');
$linea='';
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false) {
$liner=explode(': ',$line);
$linea.= $liner[1];
}
}
echo 'Search returned: '. $linea;
?>
// New script
<?php
echo("<script> var varxxx = ".$linea." </script>")
?>

Java Script for page redirecting over PHP SESSION status

I m trying to redirect pages according to PHP session status, so that, if session start () redirect to page1 else page 2
but seems like i kinda didn't done well with coding.
code goes as:
<script>
if (session_start();) {
window.location = 'page1.php';
}
else {
window.location = 'page2.php';
}
</script>
Any Help is Appreciated..
I think u want something like this:
<script>
<?php
session_start();
if($_SESSION['login'] == true) {
$_SESSION['login'] = false;
echo "window.location = 'page1.php';";
} else {
$_SESSION['login'] = true;
echo "window.location = 'page2.php';";
}
?>
</script>
First of all, session_start is a php-related function, and you are using it inside javascript.
You should prepend and append to every PHP code you want to use both these symbols:
<?php # Start
?> # End
Second Point: If you need to redirect someone to some page, use header("location") in PHP.
So your result code should be:
<?php
if(session_start()){
header("location: page1.php");
}
else{
header("location: page2.php");
}
?>
Btw.. I don't understand why you are using a "session_start" as a condition.
// create a php file first
index.php
// include js on all pages
// create a javascript file
func.js
<script type="text/javascript">
// lets create a function
function newtab(page)
{
if(page != "")
{
window.open(page,"_self","location=yes");
}
}
</script>
<?php
// no harm, we can still add javascript here
// we assume this is index.php
// start a session here
session_start();
// you need to create a switch
if(!isset($_SESSION['switch']))
{
echo '<script>newtab("page1.php")</script>';
}
else
{
echo '<script>newtab("page2.php")</script>';
}
// you can play with the switches
?>
hope this helps
Just do it with PHP:
if(session_start()){
header("Location:page1.php"); die();
} else {
header("Location:page1.php"); die();
}

To pass argument from a php file to javascript file

I am facing some trouble in passing a simple variable from a php to javascript file.
I have a form which submits through a php file which basically updates the record at the server end. And if the updation is succesful, I just want to pass the message back to the javascript where I can update it on a certain section of the page.
My codes are:
Javascript code - abc.js
function expand_cards(project, SlNo)
{
name = project['project_name'];
j = "ShowForm-"+SlNo+"";
s = "<div class='edit_project_card'>";
s += "<form method='post' action='Edit_Project.php'><div class='project_form'>
// Form Contents
s += "<div class='Form_button'> <input type='submit'> </div>";
s += "</form></div>";
$("#"+j+"").html(s);
response = $.parseJSON(data);
$("#"+j+"").html(response);
}
PHP file - Edit_Project.php
<?php
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
echo json_encode($response);
mysqli_close($connection);
?>
But the problem is the screen is printing $response variable as it is and not exactly passing it back to the javascript function as wished. I know I can use a $.post function which can can receive argument but it's a long form and passing parameters would be difficult in that.
Can anybody help me out here ?
Thanks
Dirty, but it will work:
<script type="text/javascript">
var my_var = <?php echo $some_variable; ?>
// Do something with the new my_var
some_func(my_var);
</script>
I wouldn't do too much detailed stuff with this though, if you can use AJAX that is better.
Note, this can only work on a .php file or one being read as such.
you'll want to do some variable handling in your php side because if the string is empty you'll end up with a
var my_var = ;
which will break the script. so something like:
var my_var = <?php echo "'" . $some_variable . "'";?>
if it's a string or if it's a number:
var my_var = <?php echo (empty($some_variable) ? null : $some_variable);
This is int specific, I'm sure you can come up with a function that will handle it better.
References:
empty function http://php.net/manual/en/function.empty.php
shorthand if http://davidwalsh.name/php-ternary-examples
Since you're submitting the form to the PHP file directly the browser loads the Edit_Project.php file as it would a normal page. If you want a json response to the already loaded page you'll have to use $.post or $.ajax
You can post the whole form simply by using serialize() like this:
$('#form_id').on('submit', function(e) {
// Stop the browser from posting the form
e.preventDefault();
// Post the form via Ajax
$.ajax({
url : 'Edit_Project.php',
type : 'POST',
data : $(this).serialize(),
success : function(response) {
// Here you do the HTML update
$("#"+j+"").html(response.reply);
}
});
});
The Edit_Project.php needs to be changed as well:
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
mysqli_close($connection);
/*
* As SuperDJ suggested, you need to tell the browser that it's
* receiving a JSON ojbect although he did use the wrong content type:
*/
header('Content-Type: application/json');
/*
* According to php.net most decoders should handle a simple string as
* json object but to be safe always encode an array or an object since
* you can't know how the decoder will respond.
*/
echo json_encode(array('reply' => $response));

Modifying PHP Session Variables with 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

Php Javascript Alert on Login

I need to notify the user that they logged in successfully with a pop alert to the following code. Anyone any pointers how I can add it to the php below?
Thanks.
function logged_in_redirect() {
if (logged_in() === true)
{
header('Location: /index.php');
exit();
}
}
try this code
function logged_in_redirect() {
if (logged_in())
{
echo "<script>alert('You are successfully Logged in');</script>";
echo "<script>location.href='/index.php';</script>";
}
}
You need to pass the notification to the page through get or save it to the session and then unset it. The second option is a bit harder to implement but it's less intrusive for the user (won't clutter the url).
Through GET
function logged_in_redirect() {
if (logged_in() === true)
{
$successMessage = urlencode('Authenticated successfully');
header('Location: ' . sprintf('/index.php?message=%1$s', $successMessage));
exit();
}
}
On index.php you can access the message through $_GET['message'] and display it on the page.
Through the session
First of all start the session (if it's not started already: session_start();.
function logged_in_redirect() {
if (logged_in() === true)
{
$_SESSION['successMessage'] = 'Authenticated successfully';
header('Location: /index.php');
exit();
}
}
In index.php you will have something like this (don't forget to start the session, otherwise the usperglobal $_SESSION will not be available):
if (isset($_SESSION['successMessage'])) {
echo $_SESSION['successMessage'];
unset($_SESSION['successMessage'];
}
As for the JavaScript part, you can echo the message inside the JavaScript code for the alert. However, I highly suggest you look at a templating engine (Smarty or Twig) for the HMTL/JS instead of using echo as in my example.
Try this
function logged_in_redirect() {
if (logged_in())
{
echo "<script>alert('You are successfully Logged in');
location.href='/index.php';</script>";
}
}
Just put alert("You are Logged in Successfully"); in between Script tags
OR
Call a function in onload event in body tag of html
write a function in script with same alert() looks like above.
Thats all.
try this
<?php
function logged_in_redirect() {
if (logged_in() === true)
{
?>
<script> alert("logged in"); </script>
<?php
header( "refresh:5; url=index.php" );
exit();
}
}
?>

Categories