Javascript: Terminate the program when CANCEL clicked - javascript

Scenario:
I have a confirmation pop up message where when I click the OK button it will just proceed or will save the entry that I created - this is okay.. BUT when I click the CANCEL button it will go back to the page of booking_content.php - this one is okay...
PROBLEM:
the problem now is with the CANCEL, returning back to the page is good but its still saving the entry which is when I pressed theCANCELit will not save and will return back to the page ofbooking_content.PHP`.
QUESTION:
Is there a way to *terminate the program* when I click the CANCEL? I also tried the EXIT; but its not working....
Here's my code of Javascript along with PHP:
// other if else..
else if($network == "Mass and Mobile" && $row[fldTotalDuration] == "08:00:00" && $duration >= "0 s")
{?><?php
if(sizeof($bldg) == 1)
{
echo "<script type='text/javascript'>\n";
echo "alert('$bldg[$i] station is already full.');\n";
echo "window.location='booking_content.php'";
echo "</script>";
}
else
{ ?>
<script>
var r=confirm('$bldg[$i] station is already full. Do you want to save the other networks?')
if (r==true) {
alert("OKAY BUTTON");
} else {
window.location='booking_content.php';
}
</script>
<?php
}
}
//after all the if else...
else
{
// heres my code for saving the data....
}
THANK YOU IN ADVANCE...

You do realize that PHP executes on the server to generate a large string which is then sent to the browser as an HTML file that contains the javascript don't you?
So, the code executes as follows:
The user makes request to 'booking_content.php'.
The web server executes PHP to process the 'booking_content.php' script.
The 'booking_content.php' script is executed including the else section that contains the code for saving the data.
Data is saved and HTML string is generated and sent to the user.
Browser receives the HTML and executes the javascript which prompts the user with the confirmation dialog.
Do you see the problem here? The data is saved long before the confirmation dialog is shown to the user.
The way around this is to pop the confirmation dialog before the user makes a request to 'booking_content.php'. It's usually done as an onsubmit event on the form that submits the data or manually calling the dialog function if the data is submitted via ajax.
Alternatively in cases where you need to check some data or status in the server before popping the dialog you can have a separate intermediate page to ask the confirmation. For example, create a 'booking_confirmation.php' that gets the data from the form which in turn asks the confirmation and then redirects to 'booking_content.php' when the user clicks OK (remembering to include the post data or query param).

Related

How to change the inner content of a new page from the function called at the previous page?

I am learning PHP and JS and trying to create a log in page using PHP,MySQL and JS.
Here, I am trying to check whether the login details are correct or not. if it's correct then it will redirect the user to index.php and show a message on the top Logged in Successfully.
So, On clicking on submit button PHP is going to check whether it matches the detail or not from the MySQL database, If yes then it will call a JS function which is going to redirect the user to index.php and change the inner HTML just below the header and show the message, but the problem is instead of showing the message at index.php it is showing the message at the same log-in page and before even someone sees the message the page immediately redirects to index.php.
I want that message to be shown at index.php and not at login.php. How do I do that?
PHP: If MySQLI Query return some result or not
if($count == 0){
echo "<script> email('n'); </script>";
} else {
echo "<script> email('y'); </script>";
JavaScript Function: If it receives Yes or no from PHP
function email(status) {
if (status == "y") {
document.getElementById("alert").innerHTML =
"<p class='success'> Access Granted </p>"
}
else {
document.getElementById("alert").innerHTML =
"<p class='failed'> Access Denied </p>"
}
};
HTML: The header is common for all the pages in the site and there is an external css attached to it.
<div id="alert">
</div>
This is an empty div tag which is going to be changed if js function is called to change it's innerHTML.
Please guide me.

Call Modal when PHP form submits

I have a php form that works perfectly. However, when the form submits, I want to display a modal and take the user back to the homepage. I have looked this past two hours online but have found no conclusive evidence. My current code is;
if($sentMail) //output success or failure messages
{
?><script>
$(function() {
$("#thankyouModal").modal();
});
</script>
<?php
}else{
die('Could not send mail!');
}
The form collects data then sends all data as an email. I have tried using only php, jquery, amongst everything else. I simply want a modal that says a brief thank you, your form has submitted whilst re-directing the user to the index.html page. Does anyone have any ideas?
Regards,
Michael
If you want to show the message while the form is posting (whether or not it will succeed), use jquery to swallow the onSubmit() event.
$('form').on('submit', function(e){
e.preventDefault();
$("#thankyouModal").modal();
$('form').submit();
});
If you care about if the email is successful, pass a variable back to the view and conditionally show the modal, but this will be serverside validation (will only know after form submission and re-rendering of the view). Otherwise look into doing an asynchronous post with $.ajax

On redirect notification - PHP/JS

How can I make a Modal Box/Notification Box appear when I do header redirect or some other method of redirection to a page? Basically as a Success kind of thing. Like I click on send it opens a page and then brings them back to the same page where the send button is and will show a Success box? Any ideas?
If you need to trigger some code on a PHP page through an AJAX call you can do it without directly opening that URL. You just pass that PHP URL to a call, the PHP page code is executed and the response is returned back to the page where the request originated. It would look something like this:
<span id="someButton">Button</span>
<div id="someDivOnYourPage"></div>
<script>
$('#someButton').click(function(e) {
$.ajax('page.php', {
success: function(data) {
alert(data); //This alerts 'Hello from PHP!'
$('#someDivOnYourPage').html(data);//this will set 'Hello from PHP!' inside the #someDivOnYourPage div
},
error: function() {
alert('An error occurred');
}
});
});
</script>
page.php
<?php
echo "Hello from PHP!";
?>
A more detailed explanation with downloadable examples can be found here: jQuery Ajax POST example with PHP.
If it's just a login or something similar, you can store the message in a session on whatever page you're processing and then once the page has been redirected, put that session variable into a regular variable and unset your session. Then you'll just print out whatever as HTML or Javascript.
On the page you submit to
//Do your processing
$_SESSION['someReturnMessage'] = 'Success!';
header('Location:./originalpage.php');
On originalpage.php
//Top of file
if(isset($_SESSION['someReturnMessage'])){
$message = $_SESSION['someReturnMessage'];
unset($_SESSION['someReturnMessage'];
}
...further down the page where you want the message to show...
if(isset($message){
echo $message;
}
You could also use AJAX, which may be a better fit for doing simple tasks.
Using sessions can be a bad idea though, so make sure you don't use them when there are better solutions: Error messages stored in SESSION

how to prevent a user from pressing backspace/back arrow

I have a string of surveys, one after the other. It seems that after one survey, some people are pressing backspace to go back to the previous survey and then resubmitting it with new information.
How can I stop this? I am assuming that I need some sort of Javascript script.
I have found this
Preventing backspace to go back from the current form
but it doesn't seem to help if someone is doing it on purpose, which might be the case.
Do not break the back button. This breaks the browser HCI rules.
To do this properly you need to assign a unique ID to each instance of a survey being taken. Then, when a survey is being started, check that the ID has not been submitted before.
I assume you are tracking user's progress in survey on server (through cookie). If the user has proceeded to the page N in the survey and you don't want him to go back and modify his response on page N-1, then you can present him back with the page N even though he tries to access N-1 page. That will take care of user getting back to the N-1 page by pressing back button (something he/she can do even if you block backspace button)
I can see how it can be done in PHP by creating a $_SESSION, and updating it as each form is completed.
At the beginning of each page simply check that the session correlates with the correct survey.
I'll try and give an example.
First page
$_SESSION['status'] = 1; // allowed to view survey 1
if($_SESSION['status'] != 1){
header('Location: /page' . $_SESSION['status'] . '.php');
exit();
}
// your survey
// clicks submit
// goes to 2nd page
.... 2nd page (2nd survey)
$_SESSION['status'] = 2; // updates the status to show is on the 2nd page
if($_SESSION['status'] != 2){
header('Location: /page' . $_SESSION['status'] . '.php');
exit();
}
// your survey
// clicks submit
// goes to 3rd page.. etc

Have jQuery fire Ajax request when when back button is pressed

I have a page with 80+ dynamically generated input boxes, when the user submits the form to another .php page and one of the inputs contains a value that is not numeric, it will send them back to the inputs page using: <?php header("Location: javascript:history.back()"); ?>, at the same time it registers the error in a session variable. The reason why I'm using javascript:history.back(), is because it stores the values that were in the form, even when you press the back button. But because it is caching the page I can't output the error in the same .php script, so I added a an element and some Ajax code. The Ajax code retrieves another file called error.php, this contains:
<?php
header("Cache-Control: no-cache");
session_start();
if(isset($_SESSION['error']))
{
echo $_SESSION['error'];
unset($_SESSION['error']);
}
?>
This is retrieved when the page is loaded on it own, but not when history.back() is used, it looks like the following isn't firing:
<script type="text/JavaScript">
$(document).ready(function(){
$("#error p").load("error.php");
});
</script>
Any ideas?
Thanks,
Justin
Using header("Location: javascript:history.back()") is generally ill-advised.
Use an absolute path i.e.
header('Location: /forms/input.php');
You could avoid submitting the form entirely and send the data via an AJAX call - the server could validate the data and send back either "success" or a list of validation errors.
If success, move on to the next URL (possibly specified alongside the success message)
If failed, modify the current page to indicate what the problems were. This avoids you having to re-create the whole form (as you never leave the page) but also allows for reliable server-side validation

Categories

Resources