I made a simple login using JavaScript, but record the username in a PHP session.It's a simple web chat, so I want when the chat page is loaded the user to be forced to pick an username, but after that I want to store that info ina a PHP session and if the page is reloaded for some reason to do a check if $_SESSION['UserName'] is empty and if it's not to stop the script from executing again.I put my login JS in <body onload..> and the code looks like this:
<body onload = "showUser(), showChat(), <?php if ($_SESSION['UserName']==""){
{
Login();
}?>">
I'm just learning now, so I gues I have some newb mistakes, like I'm almost sure that I'm not calling the Login() function right (it's JS function), but that's my strating point.Could anyone explain to me, how should I do the check properly and add the JS function in my PHP code?
P.S And I don't know if this really matter but if I remove the PHP code and leave liek this:
<body onload = "showUser(), showChat(),Login()">
My script is executed properly and I get everything that should be shown when the page is loaded, but when I add the PHP script and try to load the page I get blank page.I really wonder what's the reason for this too?
You cant call a js function from php. instead we have to print the js function as string in php so it will be executed as js along the html.
<body onload = "showUser(); showChat(); <?php if ($_SESSION['UserName']==""){ echo 'Login();'; }?>">
To Write efficient php code:
<body onload = "showUser(); showChat(); <?php echo (($_SESSION['UserName']=='')?'Login();':''); ?>">
You get blank page because of fatal error. which is occurred due to the javascript function you called in php (ERROR: Undefined function login() ).
You must echo the text Login(); from PHP - PHP does not execute Javascript, but you can use it to control which Javascript functions are called.
<body onload="showUser(), showChat(), <?php
if(isset(!$_SESSION['UserName']) || $_SESSION['UserName'] == ""){
echo 'Login();';
}?>">
You are effectively using PHP to create two different body tags - one for logged in users, and one for others.
Side note: it's good practice to check that an array item exists before attempting to access it: isset($_SESSION['UserName']) || $_SESSION['UserName'] checks first if $_SESSION['UserName'] has been set, then checks if it has been set to something other than an empty string.
You can simply call this as:
<?php
if($_SESSION['UserName'] == ""){
?>
<body onload="showUser(), showChat()">
<?php
}
else
{
?>
<body onload="showUser(), showChat(), Login();">
<?php
}
?>
Related
I am trying to hide our mailing address on our website, until someone cliks a button to "load" the address. I am doing it like follows:
Homepage.php:
<button onclick="test()"> Click </button>
<div> </div>
<script>
function test(){
$.ajax({url:"address.php", success:function(result){
$("div").text(result);}
})
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Address.php:
<?php
function php_func(){
echo '<span><?php echo $address; ?></span>';
}
php_func();
?>
This works in echoing the text onto homepage.php, but it's not loading the PHP function. Just showing the function as text as seen here:
I tried $("div").write(result);} and it won't even load.
$address is already defined elsewhere. Any tips?
You're trying to write code which outputs code which outputs the address. Why? You're already in the context of outputting something from the PHP code:
echo "something...";
If what you want to output is the value of $address then just output that:
echo "<span>$address</span>";
I suspect the reason you did it that way is because you're expecting the currently loaded page to parse and execute that PHP code. This is a fundamental misunderstanding of how these technologies work. The PHP code for that page executed once, on the server, and delivered the resulting HTML/CSS/JavaScript to the client.
The AJAX operation is making a new, separate request to another PHP resource which will execute on the server and output back to the client. In this case it's just outputting a string value, which the client-side JavaScript code will then write to an element on the page:
$("div").text(result);
(This is a good opportunity for you to use your browser's debugging tools and observe the AJAX request/result in the network tab, to see what's actually being sent/received. At no point should actual PHP code be visible to the browser. All of that is executed on the server.)
The reason this is important is because, if this is the case, then you are likely misunderstanding where $address is defined. If it's defined in the PHP script which rendered the page you're looking at, that doesn't mean it's defined in address.php. If the code you're showing us for address.php is the entirety of that page then $address is not defined.
So you'll need to define $address on that page.
After having said all of that... You might find it much easier not to involve AJAX for this at all in the first place. Just output the address to the page but style the <span> to not be visible. Then when the user clicks the button, make it visible. No need for the complexity of an entirely new HTTP request:
$('button').click(function () {
$('span').show();
});
span {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click</button>
<span>this is the address</span>
You don't use <?php echo inside strings; that's only used when you're in a section of the script that's outputting literal text, not executing PHP code.
If you're in PHP code doing echo, you use variable substitution or concatenation.
<?php
function php_func(){
echo "<span>$address</span>";
}
php_func();
?>
You'll need additional code to set the $address variable; I assume you just left that out for simplification in the question.
<?php
function php_func(){
echo '<span>' . $address .'</span>';
}
php_func();
?>
this should work, u can't use 'echo' and inside echo open 'php' tag to use again.... more another 'echo'
I have a file which is of php type. And I have a combination of HTML elements, javascript functions and some PHP scripts as well. I want to rerun the php script say some part of the script again and again. lets take this example:
<html>
<?php
$connection = mysql_connect('localhost','root','root');
$db = mysql_select_db('messenger');
if ($db == null)
{
echo "hello";
}
$messagecheck = "select * from Messages where destination = '$user' && status = 'ACTIVE'";
$result = mysql_query($messagecheck);
$no_rows = mysql_num_rows($result);
............
?>
<body>
........
<form>
<input type="submit">
.......
</form>
</body>
</html>
I want to run the above php script continuously for every 1 min from the same file. When I make use of location.reload() I find that complete document gets reloaded. I just want the affect the part of the page which php script accesses and not the whole doc.
How can I do that? Please help.
You can't do that out of the box, since php is called when the page is loaded.
You should take a look at Ajax or frameworks like JQuery, that embed Ajax.
As previously said by blue112 you need to use Ajax in order to get what you want.
If I did understand well what you need, a simple solution is using an iframe where you point to a file with only the php code you want to execute, and reload it every time you want.
I hope this helps
I'm trying to assign value of JavaScript variable to php session. Please see my code below -
<script type="text/javascript">
<?php $_SESSION['historyClass'] = "";?>
var myClass = $(this).attr("class");
if(myClass == 'trigger'){
<?php $_SESSION['historyClass'] = "trigger"; ?>
}
else{
<?php $_SESSION['historyClass'] = "trigger active"; ?>
}
alert('<?php echo $_SESSION['historyClass']; ?>')
</script>
In myClass variable, i'm getting 2 values
1) trigger
2) trigger active
Whatever the value I'll get, I want to store it in php session. But when I alert the session value it is always giving me "trigger active". It means it is always going to else part. I have checked the 'if' condition by alerting in it, the control is going properly in "If" and "else" part.
What is the problem? Am I doing something wrong?
Thanks in advance.
PHP is processed first, and then javascript is executed, so it's impossible to directly assign values to php variables.
instead you could send http requests from javascript (Ajax) to php scripts to save your data.
This won't work. PHP is executed on the server, and JS on the client. That means that the php is running before the JS is parsed. I suggest you look at Ajax if you want to run PHP from javascript (specifically the jQuery library and its ".get()" function).
What's happening is that the PHP is parsed, and doesn't see any JS, so it runs as normal, and sets the session to trigger, and then trigger active. Then javascript comes along on the client, and the client doesn't see any PHP code,so doesn't run it.
this wont work. the php code runs on serverside, js - on client. so php is executed before the page is shown to the user. it means that first is executed $_SESSION['historyClass'] = "trigger"; than $_SESSION['historyClass'] = "trigger active"; and obviously the value will be trigger active
yes you are doing something wrong.
javascript runs on client side and php on server side. so your code runs first on server side and then on the client.
thats why you can't do it like you did. a common way to transfer javascript data to a php script is, writing the value to a hidden field, so that it gets submitted to the server.
just create a hidden field and fill it with a value from javascript
<script type="text/javascript">
function valToPHP(name,value){
document.getElementById(name).value = value;
}
</script>
...
</head>
<body>
<input type="hidden" id="myField" name="myField" value="" />
...
you can then read it in your php script like that
$_GET["myField"] or $_POST["myField"]
this depends on your method of the form
Hi i am not a php developer, ive never touched it before. but i have been asked to add a google shopping cart tracking code to a website. when someone completes an order then get sent to finishorder.php. when i go the finishorder.php file it looks like this:
include(dirname(__FILE__)."/init.php");
$GLOBALS['ISC_CLASS_ORDER'] = GetClass('ISC_ORDER');
$GLOBALS['ISC_CLASS_ORDER']->HandlePage();
which just looks like server script to me (coming from a .net background), so i presume i cannot add the javascript here, how does php decide get the layout for this page? how can i add the javascript code to this page.
You can do this:
include(dirname(__FILE__)."/init.php");
$GLOBALS['ISC_CLASS_ORDER'] = GetClass('ISC_ORDER');
$GLOBALS['ISC_CLASS_ORDER']->HandlePage();
echo '<script type="text/javascript">YOUR JS HERE</script>';
OR
<?php
include(dirname(__FILE__)."/init.php");
$GLOBALS['ISC_CLASS_ORDER'] = GetClass('ISC_ORDER');
$GLOBALS['ISC_CLASS_ORDER']->HandlePage();
?>
<script type="text/javascript">YOUR JS HERE</script>
Hmm?
But I think that HandlePage() method will do something with our page so I'd look inside this method Class ISC_ORDER->handlePage() what it does... You can then echo Your within this method on appropriate place...
EDIT:
<?php
echo '<script type="text/javascript">//<!--
alert("Hello to multiline JS script");
alert("Do You get it?");
//--></script>';
?>
You can add javascript inside a php code as
<?php echo "<script> alert('this is a javascript code')</script>"; ?>
You can add script in PHP page by 2 ways
The first way is to add it in PHP tags
<?php
//PHP CODE
if($_POST['submit']){
echo '<script>alert('Hello')</script>';
}
?>
The second way is to add it after PHP code
<?php
//PHP CODE
?>
<script>
alert('Hello');
</script>
I have a form with Name : input and a submit. When pressed, it posts to the same php file. My first check is basically if(!$name) { call jquery to insert error class }. I have the jquery set up in a function but I'm not sure how to call the function from the if statement.
You need to do your check in javascript / jquery and avoid posting to the php file until the javascript validation is completed / satisfactory.
Then in php you need to validate again in case the visitor has javascript disabled.
Don't use jquery in this case. Just have PHP output the appropriate class in the HTML, since PHP can not directly (or even indirectly) call javascript functions:
<?php
$name_error = empty($name); // $name_error is true/false;
?>
[...snip...]
<div class="this and that <?php if ($name_error) { echo 'error classname here'; } ?>">
<?php if ($name_error) { echo 'error message here'; } ?>
</div>
Trying to get PHP to call javascript to do what PHP can already do perfectly well on the server is a waste of effort. It's like driving to a payphone instead of using the perfectly good phone that's already sitting on your desk.
I think my answer for this question should prove helpful.
In a nutshell - your PHP script will need to send data back to the client that will let you identify which field is in error and why. jQuery will then be responsible for altering the field as you see fit.