Logout Button with PHP Classes - javascript

Right now I'm using jquery to run a php script which isn't working, i know that php is a server side script and you can't run the script from jquery, in that case what is the best way to call a php function within a class from the browser?
This is the class where the logout function is defined
class Profile
{
private function logout()
{
$_SESSION = array();
session_destroy();
}
This is the php page where i want to call the function upon click of the logout button
<?php
include_once('profileclass.php');
$user = new Profile($name, $id);
?>
<html>
<head> </head>
<body>
<input type='button' value='logout' id='logout'>
<script>
$(function() {
$('#logout').click(function() {
<?php $user->logout(); ?>
}
});
});
</script>
</body>
</html>

Do not mix PHP with Javascript, since PHP code is executed before the browser renders the html on page. Instead, use $_POST global variable, which will contain the data submitted to your page.
Use:
<?php
include_once('profileclass.php');
$user = new Profile($name, $id);
if ($_POST['logout'] == "<some_value>") {
$user->logout();
}
?>
<html>
<body>
<form method="post">
<input type='submit' value='<some_value>' name='logout'>
</form>
</body>
</html>
UPDATE:
Also, make your logout method public, so that it can be accessed outside your Profile class:
class Profile {
public function logout() { // change is in this line
$_SESSION = array();
session_destroy();
}
}

Frontend
$('#logout').click(function() {
$.ajax({
url: '/logout.php', // Script where logout calls
type: 'post'
});
});
Backend (logout.php)
$user = new Profile();
$user->logout();

Related

Is the function binded to the button always executed or did I make a mistake?

So I have this PHP page, with at the start some unimportant stuff and a session opening :
<?php
session_start();
?>
I want the disconnect button to appear only if the user is already connected, which means that $_SESSION['Pseudo'] is set. If this is the case, I create a button, and bind to that button a function to destroy the session. The problem is, each time I go on this page, the session is destroy, even though it's in a condition.
Here's my code :
<?php
if (isset($_SESSION["pseudo"])) {
echo '<p><button type="button" id="deco">Disconnect</button></p>';
}
?>
<script>
let btn = document.getElementById('deco');
if (btn) {
btn.addEventListener('click', updateBtn);
function updateBtn() {
<?php
session_destroy();
?>
window.location.href = "/"
}
}
</script>
Any clue ?
You cannot combine PHP within Javascript like that.
When you're doing , it's not a part of the Javascript. It's PHP code and is executed as part of the PHP code in the file.
This means that it has nothing to do with the javascript aspect. your updateBtn function is effectively, when the page source code loads:
function updateBtn() { window.location.href = "/" }
What you really want to do is make it so that when someone clicks the button, it takes them to a logout page or a page with a logout query param.
eg.
<?php
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
session_destroy();
echo 'You have successfully logged out!';
}
if (isset($_SESSION["pseudo"])) {
echo '<p><button type="button" id="deco">Disconnect</button></p>';
}
?>
<script>
let btn = document.getElementById('deco');
if (btn) {
btn.addEventListener('click', updateBtn);
function updateBtn() {
window.location.href = "/?action=logout"
}
}
</script>

Call PHP on button click

I have the following button:
<input type="submit" name="kudos_button" value="★ Give kudos"/>'
And for testing purpose, I made a PHP script like this after the </html>:
<?php
if(isset($_POST['kudos_button'])){
$message = "Pressed";
echo "<script type='text/javascript'>alert('$message');</script>";
//and then execute a sql query here
}
?>
It all works fine, when pressing the kudos_button the message shows up. But the problem is that when the user refreshes the page, the message shows up again. And I get the following message:
The page that you're looking for used information that you entered.
Returning to that page might cause any action you took to be repeated.
Do you want to continue?
Any tips how I can avoid this, so the button does not press again when refreshing?
If you don't want to navigate to a new page, then you can't use a regular form submission.
Make the HTTP request with JavaScript instead.
e.g.
const form = document.querySelector("form");
const responseHandler = response => response.json();
const dataHandler = data => {
alert(data.message);
};
const submitHandler = event => {
event.preventDefault()
const data = new FormData(form);
const url = "/path/to/dedicated/webservice/that/returns/json";
fetch(url, { method: "POST", body: data }).then(responseHandler).then(dataHandler);
};
form.addEventListener("submit", submitHandler);
MDN has a guide on using fetch.
Then your server-side code would look something like:
<?php
// Execute a sql query here
header("Content-Type: application/json");
$message = "Pressed";
echo json_encode( [ message => $message ] );
Here is my solution:
<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<input type="submit" name="kudos_button" value="★ Give kudos"/>
</form>
<?php
if(isset($_POST['kudos_button'])){
$message = "Pressed";
echo "<script type='text/javascript'>alert('$message');</script>";
//and then execute a sql query here
}
?>
Should be worke fine.
But you should know that PHP works regardless of the alert. Either way, your SQL statement will be executed after the button is pressed.
JavaScript is a Client Based Script and PHP a Server Based Script two different things.
--- EDIT ---
I builded a Function Based PHP Script which is calling the alert and feel for 5 seconds to sleep so the alert can shown up.
Here is my finished solution:
<form name="form1" method="POST" action="./" >
<input type="submit" name="kudos_button" value="★ Give kudos"/>
</form>
<?php
if(isset($_POST['kudos_button'])){
session_start();
$_SESSION["Button_onClick"] = 1;
$message = "Pressed";
if ($_SESSION["Button_onClick"] == 1) {
Button_onClick();
$_SESSION["Button_onClick"] = 0;
if ($_SESSION["Button_onClick"] == 0) {
BackLoop();
}
}
}
Function Button_onClick(){
$message = "Pressed";
echo ("
<script type='text/javascript'>
alert('$message');
</script>
");
SQL_Statement();
}
Function SQL_Statement() {
//and then execute a sql query here
}
Function BackLoop() {
session_destroy();
echo("
<script>
setTimeout(function () {
//Redirect with JavaScript
window.location.href= './';
}, 5000);
</script>
");
}
?>
Just in case for that someone have questions. I added the setTimeout function so I could see the changes on the website. If you don't want any infos after the alert (user case), you can delete the function. You only need window.location.href= './';.

How to call a php function on a html text click?

I want to call php function while call that function I need to pass parameter, when click on some text, It has to call the method called test();
How to do this.
I don't know anything about ajax.I have taken this code to try it.To try I have used simple code it is also not working.
This is Ajax.html file
<!DOCTYPE html>
<html>
<head>
<body>
<p>Click Me</p>
<script>
$(document).ready(function() {
$("p").click(function(){
$.ajax({
url:"script.php", //the page containing php script
type: "POST", //request type
success:function(result){
alert(result);
}
});
});
})
</script>
</body>
</head>
</html>
script.php contains,
<?php
function test(){
echo "Hello";
}
?>
how to call php function when user click on some text.where I have to call that test() method. Can Any one help me?
Either you need to call when page called
<?php
test()//mind it
function test(){
echo "Hello";
}
?>
Or use any param like name of action
<?php
if(isset($_GET['action']) && $_GET['action']==1){
test()//mind it
}else{
otherFunc()//mind it
}
function test(){
echo "Hello";
}
?>
Set action in url
url:"script.php?action=1",

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>

How do I pass a variable from one php file to a javascript file?

I am currently trying to make a site where I put in info in on my html side, it send the info to the php file and grabs info from another site depending on what you put in on the html side.
To make this more clear this is how it works:
You put in your username in the html site(where the javascript code
is).
Then it sends your username to the php file.
The php file gets the information, puts it in a link and request it.
It grabs information from this request (highscores page).
This is where it stops.
I don't know how to return the information to my javascript file.
This is my code:
html/javascript page:
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<script>
function test() {
var username = "Exzib";
window.location.href = "grabinfo.php?username=" + username;
}
</script>
</body>
</html>
This is my php file: (grabinfo.php)
<html>
<head>
</head>
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
echo $formatxp;
}
?>
<body>
</body>
</html>
So how do I proceed to send the $formatxp to my javascript?
Thanks
So what you do is execute:
window.location.href = "grabinfo.php?username=" + username;
This causes the browser to navigate to grabinfo.php and display the information that you want. Except that you don't want the information to be displayed, you want to retrieve it into a JavaScript variable, right?
To do so, don't set window.location.href. Instead call your script using AJAX. You'll find plenty of tutorials on AJAX out there. This will allow you to capture the output of your PHP script.
Change the following line
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
to
$formatxp = str_replace(array('$',',','.',' '),'',$xp);
And to pass the variable to Javascript you can do something like this.
<script type="text/javascript">
var $formatxp = '<?php echo $formatxp; ?>';
</script>
Write a script tag and set the variable equal to your PHP variable.
<script>
var thing = '<? echo $formatxp; ?>';
</script>
This is going to be easy as you already include jQuery. (Using ajax)
Look
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<label>Type your username:<input id="username" type="text"></label>
<input id="submit-button" type="button" value="Get my highscores!">
<p id="response"></p>
<script>
//When user clicks "submit-button" button
$("#submit-button").on('click', function() {
var username = $("#username").val();
//We request our php with the username
$.get("grabinfo.php?username=" + username, function(xpValue) {
//When we receive the response from php then we add it to a "p" tag
$("#response").text("LOL your xp is: "+xpValue+". NOOOOOOOB!!");
});
});
</script>
</body>
</html>
And that's it!
More info at http://api.jquery.com/on/
And http://api.jquery.com/get/
http://api.jquery.com/text/
http://api.jquery.com/val
And well the whole jQuery API documentation http://api.jquery.com
EDIT:
OH. You have to change grabinfo.php. It should only have this:
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
if(empty($formatxp)) {
echo "ERROR: Invalid could not find xp with username {$username}";
}
else {
echo $formatxp;
}
}
else {
echo "ERROR: Invalid arguments";
}

Categories