Materializecss Toasts with PHP - javascript

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>";
}`
?>

Related

Clearing a Session variable using 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.

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

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.

Show Alert message and redirect after click Ok

I am Using redirect function of Codeigniter with alert of JavaScript. I want to display message first before redirect to other page, but my code just directly redirect the page without displaying alert message. I need code in method of controller of codeigniter.I used code as follows in method of controller:
echo "<script type='text/javascript'>alert('Duplicate Users')</script>";
redirect('auth/login'),'location');
Plz Advice me
Waiting for Response
Thank You very Much for supporting me.
See this ..
Server code (PHP -> redirect) is fired up before Client Code (JS -> alert). There are several solutions to this but the easiest one is to use one type of code for the functionality (either PHP or JS) ..
Let's use PHP to fire up JS for now, since that's what you're using ..
echo "<script>alert('Duplicate Users') ; window.location.href = 'auth/login'</script>"
<script>
alert("Duplicate Users");
window.location.href = "auth/login";
</script>

Calling multiple html page from php consecutively

I am not well versed in php. I tried different answer from stackoverflow but was not successful in solving the problem.
I got a HTML form with a submit button. After submitting I call a php script and which in turn calls an executable file which runs some algorithms on the submitted data from the html. At the end I echo the result of the analysis through the php.
<?php
$ex=shell_exec("...");
if($ex == "Run Successfully\n"){
echo"<html>
<meta http-equiv= refresh content='0.1;URL=--.txt'>
</html>";
}
?>
Till this works fine but my algorithm takes 30-40 sec to run and all that time my original html page remains in screen which looks like nothing is happening there. So I created a new html page with a progress bar animation. Now I want to show the progress bar while the executable is running and when the result is available I want to replace the progress bar page with the result page as before.
I tried echo file_get_contents("waiting.html");
header ("location: waiting.html");
But none of them works as I planned. All the time they are coming up only after the executable finish working and not before that.
If someone can help me with some suggestion I shall be grateful.
Thanks in advance.
This is where jQuery and AJAX would work very nicely. What you could do is start with the loading animation, and use jQuery to call the php file with the shell_exec with ajax. Once the ajax is .done(), then you can replace the text with the results. If you need me to clarify, just let me know.
However, if you don't want to use AJAX, PHP is run line by line. Therefore, you would want to put your progress bar before the shell_exec. This would mean that you would not be able to use header location since headers have already been sent.
Edit (AJAX Example):
This would be a quick example of how to make this happen.
Create two php files:
progress.php
Load jQuery
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url:'algorithm.php',
type: 'post',
cache: false,
success: function(data) {
//Replace with how you want to format the page
}
});
});
</script>
Loading Bar
algorithm.php
<?php
$ex=shell_exec("...");
if($ex == "Run Successfully\n"){
die('{"status":"success"}');
}
?>
Now you don't have to use json as an output. You can also have html output. Let me know if I should clarify anything.

Categories