Clearing a Session variable using javascript - javascript

I have been searching the interwebs for this, however, can't seem to find a solution. I have a PHP script that sets a $_SESSION['x'] and I display it on a page if it is set using a bootstrap alert. However, the darn thing never goes away and I can't figure out how to do it. I'm not trying to edit or insert anything into the variable simply just trying to unset it to "dismiss" the error.
Here is my code:
HTML page with PHP code to display error alert.
if(isset($_SESSION['x']) && !empty($_SESSION['x'])){
echo "<div class='alert alert-danger alert-dismissible fade show' role='alert'>" . $_SESSION['x']. " Error: " . $_SESSION['errorCode']."
<button id='close' type='button' class='close' data-dismiss='alert' aria-label='Close'>
<span aria-hidden='true'>×</span>
</button>
</div>";
}
JS File
$("#close").click(function(){
$.get("../php/scripts/clear/employeeError.php");
});
PHP File to clear variable
session_start();
if(isset($_SESSION['x'])){
unset($_SESSION['x']);
}
echo $_SESSION['x']; // Just to see if it unsets
What I want to happen is when I click on the dismiss button to unset $_SESSION['x'] while not refreshing the page. Once the dismiss button is clicked the alert will dismiss on the current page and when you go back to the page later, the $_SESSION['x'] is unset so you don't see the error again.

I think you're pointing out some key concepts about server side and client side programming. You're using PHP to render HTML page, after rendering any change on PHP environment won't affect your already rendered page.
Please see;
How to assign php variable in JavaScript value assign?
set or change php variable in javascript

Here is what I have figured out to work
$(function () {
$('.close').click('.close', function(){
$.get('php/scripts/clear/employeeError.php', function(data){
alert("Server Returned: " + data); //Used to verify script runs
});
return false;
});
});
Basically what happens now is I use this inline script to listen for the .close and then it will call the script to unset the session variable.

Related

Give div a style when redirecting with header

I am redirecting to a page with a header link header('Location: ../index.php?resp=resp2#contact'); and when I press that link I want my div to start with the style left: 12vw. I don't want this to happen when you refresh the page. How can I do this?
I tried stuff with a resp in the link, but I already make use of resp's and I don't think it's possible to send 2 resp's at once? I also tried doing it with javascript so when a page is reloaded it will give the style, but then it also triggers on refresh.
It doesn't matter if it is javascript, JQuery , php or just normal html/css, I just hope I'll get it to work.
You could set a session variable before the redirection, if the variable is set, echo that style and clear the given variable. That way, on refresh, it will not echo the style.
Page with redirection:
// session_start(); // if not yet started
$_SESSION['style_div'] = true;
header('Location: ../index.php?resp=resp2#contact');
exit; // just in case;
Page with given DIV:
// ... [probably some code]
// session_start(); // if not yet started
if(isset($_SESSION['style_div'])){
unset($_SESSION['style_div']);
echo '<div style="left: 12vw ...">';
}else{
echo '<div style="...">';
};
// ... [rest of code]

insert php into javascript

I write some html, javascript and php code that normally have to execute php code when a html button is pressed if you click on "ok" on the "confirm box", so there is my html code :
<input onclick="logout()" name="logout" type="submit" value="Logout me" />
Javascript and php code :
function logout() {
if (confirm("Are you sure you want to logout ?") == true) {
<?php echo "Hello world !"; ?>
} else {
<?php echo "Goodbye world !"; ?>
}
}
I think that the javascript code work because when i click on the html button the confirm box appear like it has to appear, but the php code is not executed.
Please if someone would help me it will be greatfull.
You can't use php in javascript because php is a serverside programming lenguage and javascript is a client side programming lenguage, so php is executed (by the server) before javascript (that is executed by the browser of the user).
You have to use Ajax requests for your needs.
Quickstart Ajax guide: https://www.w3schools.com/xml/ajax_intro.asp
Even though it is possible to write JS inside of PHP, I don't think this is the way to solve this problem. You can only (as far as I know) echo PHP values inside JS that is executed inside tags, when you write HTML inside .php files.
PHP is indeed server side and the Javascript is in this situation client side. You're thinking wrong.
First you should extract your logout functionality to a logout.php file for example. Then you could do either one of the two:
When you really want to use the logout function as a direct event listener to the onClick event on your input, your logout callback function should make an AJAX call to logout.php, which logs out your user. See the answer from #Helio to see more about AJAX.
Your input should be placed inside a <form>, which has an action attribute, that calls to your logout.php. Then when submit is called, it is available to you through the $_POST superglobal, and you can check if it is pressed. Then you simply log out the user.
That doesn't appear to be valid Javascript.
Within the Javacript function, you are dropping a PHP statement as if you were writing it to the HTML, this will not work. I'm surprised you got the dialog to popup.
PHP is a server side language and Javascript is not, therefore you should not even call PHP code like that from any kind of Javascript.
To help your curiosity, you could get away with using the document.write() function, but don't use this.
I would recommend rewriting your function to redirect to a specific PHP page.
function logout() {
if (confirm("Are you sure you want to logout ?") == true)
{
// try to avoid this....but still works
document.write('<?php echo "Hello world !"; ?>');
// try this instead
window.location.href = '/helloworld.php';
}
else
{
// try to avoid this....but still works
document.write('<?php echo "Goodbye world !"; ?>');
// try this instead
window.location.href = '/goodbyeworld.php';
}
}

Materializecss Toasts with PHP

So I'm making this web control panel but I'm not good with JS. I'm using MaterializeCSS + HTML + PHP for the DB login and so on.
I would like to have the following simple functionality but for some reason I'm failing.
I'd like to fill in the username and password in my form and press Log in. Since I'm not sure how Toasts work, I suppose once I switch the page the Toast actually disappears so maybe it's better to display the toast in the new Account page that opens instead of the Login page itself. I tried both but it doesn't appear.
Code to show Toast:
echo "<script> Materialize.toast('Login successful!', 3000, 'rounded') </script>";
I found a topic somewhere in Russian saying this has a problem with DOM and used its solution without success again.
Note: I already use other JS-dependent components such as Modals and Tooltips.
Console error: Uncaught ReferenceError: Materialize is not defined
I had 2 problems. Most importantly, I was testing the code in an IF that wasn't even executed. Stupid me. Secondly, I wasn't using onDocumentReady - $(function(){});
The document referrer is just to check which page sent me there but here's my working code to create a MaterializeCSS Toast from PHP:
echo "
<script>
$(function(){
if (document.referrer == 'http://yourdomain/index.php?p=Login'){
Materialize.toast('Login successful', 2200, 'rounded')
}
});
</script>";
I had the same problem with one of my PHP scripts. In the end after a lot of research I found that I had not included JQuery. Materialize CSS needs JQuery loaded before materialize.js file. Make sure that jquery is loaded. The console error shows up because JQuery is not loaded.
I tested this code on my localhost without jquery toast doesn't work but when loaded it works fine.
<?php
if (isset($_GET['msg'])){
$msg = $_GET['msg'];
echo "<script>Materialize.toast('$msg', 3000, 'rounded');</script>";
}
?>
you can put your if condition in php like this
<?php
`if (document.referrer == 'http://yourdomain/index.php?p=Login')
{
echo "
<script>
Materialize.toast('Login successful', 2200, 'rounded');
</script>";
}`
?>

How to stop JavaScript alert from refreshing page?

I am teaching myself, so I apologize in advance if this is a 'newbie' question, but I have searched the internet and cannot find a solution.
So I've created a HTML form, and in that form I have added a Dropzone.js where people upload a file. When finished they click a button which saves it into a MySQL form, that all works great. The issue is when people click the button before the file finishes uploading. To counteract this issue, I've created an 'If Statement' that checks if the uploaded file exists. If it hasn't uploaded, then a JavaScript alert is triggered, which all works, but it refreshes the page, which erases all the imputed data.
// This is when the button is clicked
if(isset($_POST['Upload'])){
if (file_exists(blah blah) {
//All my MySQL stuff is in here
//If it isn't uploaded
} else {
echo '<script language="javascript">';
echo 'alert("Please upload at least one file")';
echo 'return false';
echo '</script>';
}}
Despite the 'return false'; it still resets the page?
Any help would be appreciated, thanks!
Can you show me the all code. You can do it with lots of methods i do it with validation. you can set a variable which increase on file upload. if variable value zero then return false form will not submit.
Php does not support like this echo 'return false'. you have to use JavaScript validation for this purpose.

Update MySQL database with AJAX

I have a form with a submit button and a close button. If a user enters something and hits the submit button, an answer will be posted and saved inside the database. If a user clicks the close button, inside the database an entry will be updated with the current timestamp.
Everything is working fine but now I would like to make those changes if someone clicks the close button with AJAX so that I do not have to reload the page.
The code for my submit button is:
<input type='submit' id='setclosed' value='Close Ticket' name='setclosed' class='btn btn-warning' />
Now if someone clicks the submit button, the followin code will be activated inside my current file (so no external file for php processing):
if (isset ($_POST['setclosed'])) { // Setze Status auf Closed
$updatecontent_success=array('stamp_closed'=>$localtime);
updateContractTicket($show_details,$updatecontent_success);
}
What do I have to do so that the database entry will be updated, but the page does not reload?
Here is a quick AJAX example to get you going. You should separate you PHP and Javascript/HTML code. I'll write out the two files.
In your HTML file you'll have the html code and the javascript that will make the request, and then alert the user that the request went through. Make sure that your form doesn't submit anything.
-HTML
<button type='button' id='setclosed' name='setclosed' class='btn btn-warning'>Close Ticket</button>
-Javascript
$('#setclosed').click(function() {
$.post('ajax.php',
{ cmd: 'setclosed' },
function(data) {
alert('AJAX request was made');
}, 'json'
);
});
The ajax sends a POST variable read by the PHP as $_POST["cmd"]. This will let your php execute the necessary code for that command, echo back a status, and then exit the php file.
-PHP
if ($_POST["cmd"]=='setclosed') {
$updatecontent_success=array('stamp_closed'=>$localtime);
$updateContractTicket($show_details,$updatecontent_success);
echo json_encode(array('Status' => 'Ok'));
exit(0);
}
Let me know if anything is unclear.

Categories