JavaScript implemented in PHP code | if-statement not working - javascript

I'm in a bit of a problem and cannot seem to spot my mistake.
Here's why:
I want to use a simple PHP if-statement to check if my form has been submitted and if it has, open a JavaScript confirm dialogue to eventually execute deletion from the database. But the code always circles through the wrong statement and it says: "Deleting has been cancelled." (code below).
Thanks for your time.
PHP code:
if (!isset($_POST['delButton'])){
echo "Selection is followed by a confirming window.";
}
else if(isset($_POST['delButton']) && isset($_POST['s_name'])){
if(jsconfirm()){
$sql = MySQL_query("DELETE FROM table_1 WHERE name = \"".$_POST['s_name']."\"");
if($sql){
jsalert("Entry has been deleted!");
}else{
jsalert("Deleting went wrong.");
}
}else{
jsalert("Deleting has been cancelled.");
}
}
Javascript:
function jsalert($s) {
echo "<script>";
echo "alert(\"".$s."\");";
echo "</script>";
}
function jsconfirm(){
echo "<script>";
echo "if(confirm(\"Delete Account?\")){return true;}else{return false;}";
echo "</script>";
}

It's not that your if statement isn't working. It's that you aren't actually communicating between JS and PHP.
When you load a page using a PHP script, then what you echo out becomes the contents of the page.
For example, this PHP would produce this HTML/JS:
<?php
echo "<script>";
echo "alert('hello');"
echo "</script>";
?>
-
<script>
alert('hello');
</script>
If you serve up this file, you will see a page that shows you an alert box stating 'hello'. But that JS code doesn't execute until your PHP code is finished running. So your JS does not communicate with your PHP at all.
If you want something to happen on your server as the result of something done with JS, you're going to need to use AJAX. There are numerous tutorials around the Internet that cover this topic, as it tends to be a bit broad for a Stack Overflow answer.

Perhaps this will help a bit. I'm a beginner myself but this is how I would solve this:
You haven't provided your HTML form, but I have a simple example. This could be a list of the names of your friends and a delete button to wipe them from your friends list. The basic HTML would look something like this:
<!DOCTYPE html>
<html>
<body>
<form>
<p>Peter</p><button>Delete</button>
<p>Frank</p><button>Delete</button>
<p>John</p><button>Delete</button>
</form>
You ultimately want this form to submit data to your PHP function. So you need to tell the form where to send the information upon submit. That's done within the opening tag of the form, like on line 4.
<!DOCTYPE html>
<html>
<body>
<form action="test.php" method="post" id="myForm">//meaning I'm sending the data in the form by *POST* to the file *test.php* in the same folder. The file test.php contains the php code that will update the database.
<p>Peter</p><button >Delete</button>
<p>Frank</p><button >Delete</button>
<p>John</p><button >Delete</button>
</form>
Then you have to have a button to actually trigger the submit action. You can add that function to each Delete button, as below.
<!DOCTYPE html>
<html>
<body>
<form action="test.php" method="post" id="myForm">
<p>Peter</p><button type="submit" >Delete</button>
<p>Frank</p><button type="submit" >Delete</button>
<p>John</p><button type="submit" >Delete</button>
</form>
So, if you would click on Delete now, the data would be posted to your php file. But you don't want that to happen yet! You want to serve a pop-up to your user first and get confirmation. So you make the button trigger a JS function, like this:
<!DOCTYPE html>
<html>
<body>
<form action="test.php" method="post" id="myForm">
<p>Peter</p><button type="submit" onclick="jsalerts()">Delete</button>
<p>Frank</p><button type="submit" onclick="jsalerts()">Delete</button>
<p>John</p><button type="submit" onclick="jsalerts()">Delete</button>
</form>
So, as soon as the Delete button is clicked, the function jsalerts() is executed. This should of course create the confirm box. The basic function could work like this (modified from the JS tutorial at www.w3schools.com):
function jsalerts() {
if (confirm("Press a button!") == true) {
alert("Deleting has been confirmed.");
} else {
alert("Deleting has been cancelled.");
}
}
Trouble is, this function does not stop the Submit action. So regardless of the user's choice, the form will be submitted. And if the user clicked Cancel, that's not what you want. On the other hand, if the user clicked Confirm, you don't want to serve him an alert, you just want the form to continue submitting.
So essentially you want to prevent the default behaviour "submit" of your Delete button if the user clicks Cancel. And JS has a method just for that, unsurprisingly called the preventDefault method. You could implement it like this:
function jsalerts() {
if (confirm("Press a button!") == false) {
alert("Deleting has been cancelled.");
event.preventDefault();
}
So this way the normal process of submitting the form would commence, except when the user clicks cancel.
This means that in your PHP you would only have to create the update database logic and not bother with the cancel or confirm.
So, to wrap it up, this would be your HTML:
<!DOCTYPE html>
<html>
<body>
<form action="test.php" method="post" id="myForm">
<p>Peter</p><button type="submit" onclick="jsalerts()">Delete</button>
<p>Frank</p><button type="submit" onclick="jsalerts()">Delete</button>
<p>John</p><button type="submit" onclick="jsalerts()">Delete</button>
</form>
and this would be your JavaScript:
function jsalerts() {
if (confirm("Press a button!") == false) {
alert("Deleting has been cancelled.");
event.preventDefault();
}
Let me know if it works. And if any more experienced coders have input that can improve my work, please comment. Thanks.

Related

How to prevent data submission after refresh [duplicate]

I think that this problem occurs often on a web application development. But I'll try to explain in details my problem.
I'd like to know how to correct this behavior, for example, when I have a block of code like this :
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
die();
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
When the form gets submitted, the data get inserted into the database, and the message Operation Done is produced. Then, if I refreshed the page, the data would get inserted into the database again.
How this problem can be avoided? Any suggestion will be appreciated :)
Don't show the response after your create action; redirect to another page after the action completes instead. If someone refreshes, they're refreshing the GET requested page you redirected to.
// submit
// set success flash message (you are using a framework, right?)
header('Location: /path/to/record');
exit;
Set a random number in a session when the form is displayed, and also put that number in a hidden field. If the posted number and the session number match, delete the session, run the query; if they don't, redisplay the form, and generate a new session number. This is the basic idea of XSRF tokens, you can read more about them, and their uses for security here: http://en.wikipedia.org/wiki/Cross-site_request_forgery
Here is an example:
<?php
session_start();
if (isset($_POST['formid']) && isset($_SESSION['formid']) && $_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
echo 'Process form';
}
else
{
$_SESSION["formid"] = md5(rand(0,10000000));
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="hidden" name="formid" value="<?php echo htmlspecialchars($_SESSION["formid"]); ?>" />
<input type="submit" name="submit" />
</form>
<?php } ?>
I ran into a similar problem. I need to show the user the result of the POST. I don't want to use sessions and I don't want to redirect with the result in the URL (it's kinda secure, I don't want it accidentally bookmarked). I found a pretty simple solution that should work for the cases mentioned in other answers.
On successfully submitting the form, include this bit of Javascript on the page:
<script>history.pushState({}, "", "")</script>
It pushes the current URL onto the history stack. Since this is a new item in history, refreshing won't re-POST.
UPDATE: This doesn't work in Safari. It's a known bug. But since it was originally reported in 2017, it may not be fixed soon. I've tried a few things (replaceState, etc), but haven't found a workaround in Safari. Here are some pertinent links regarding the issue:
Safari send POST request when refresh after pushState/replaceState
https://bugs.webkit.org/show_bug.cgi?id=202963
https://github.com/aurelia/history-browser/issues/34
Like this:
<?php
if(isset($_POST['uniqid']) AND $_POST['uniqid'] == $_SESSION['uniqid']){
// can't submit again
}
else{
// submit!
$_SESSION['uniqid'] = $_POST['uniqid'];
}
?>
<form action="page.php" method="post" name="myForm">
<input type="hidden" name="uniqid" value="<?php echo uniqid();?>" />
<!-- the rest of the fields here -->
</form>
I think it is simpler,
page.php
<?php
session_start();
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
$_SESSION["message"]="Operation Done";
header("Location:page.php");
exit;
}
?>
<html>
<body>
<div style='some styles'>
<?php
//message here
echo $_SESSION["message"];
?>
</div>
<form action='page.php' method='post'>
<!--elements-->
</form>
</body>
</html>
So, for what I needed this is what works.
Based on all of the above solutions this allows me to go from a form to another form, and to the n^ form , all the while preventing the same exact data from being "saved" over and over when a page is refreshed (and the post data from before lingers onto the new page).
Thanks to those who posted their solution which quickly led me to my own.
<?php
//Check if there was a post
if ($_POST) {
//Assuming there was a post, was it identical as the last time?
if (isset($_SESSION['pastData']) AND $_SESSION['pastData'] != $_POST) {
//No, Save
} else {
//Yes, Don't save
}
} else {
//Save
}
//Set the session to the most current post.
$_session['pastData'] = $_POST;
?>
We work on web apps where we design number of php forms. It is heck to write another page to get the data and submit it for each and every form. To avoid re-submission, in every table we created a 'random_check' field which is marked as 'Unique'.
On page loading generate a random value and store it in a text field (which is obviously hidden).
On SUBMIT save this random text value in 'random_check' field in your table. In case of re-submission query will through error because it can't insert the duplicate value.
After that you can display the error like
if ( !$result ) {
die( '<script>alertify.alert("Error while saving data OR you are resubmitting the form.");</script>' );
}
No need to redirect...
replace die(); with
isset(! $_POST['name']);
, setting the isset to isset not equal to $_POST['name'], so when you refresh it, it would not add anymore to your database, unless you click the submit button again.
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
isset(! $_POST['name']);
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
This happen because of simply on refresh it will submit your request again.
So the idea to solve this issue by cure its root of cause.
I mean we can set up one session variable inside the form and check it when update.
if($_SESSION["csrf_token"] == $_POST['csrf_token'] )
{
// submit data
}
//inside from
$_SESSION["csrf_token"] = md5(rand(0,10000000)).time();
<input type="hidden" name="csrf_token" value="
htmlspecialchars($_SESSION["csrf_token"]);">
I think following is the better way to avoid resubmit or refresh the page.
$sample = $_POST['submit'];
if ($sample == "true")
{
//do it your code here
$sample = "false";
}

Php code to modify a document element

I am trying to build a PHP webpage with the following behaviour:
1- A client access the webpage (that contains some buttons);
2- When the webpage is loaded, the PHP script opens a file stored on the server and, based on the information in this file, enables/disables some of the buttons, so that the client can see the webpage with the correct buttons enabled or disabled.
To enable/disable buttons, I know I can use javascript, while to read the file on the server I use PHP as stated above.
How do I put the two things together? Or should I use a PHP code equivalent to the following javascript line:
<script>document.getElementById("button1").disabled = true;</script>
At first I thought that inserting this line in the PHP code was the solution, but then I found out that this can't work for obvious reasons.
Thanks for the help!
Is it correct if I add the following javascript function in the head section of my webpage?
<script>
function enableButtons() {
<?php
if($state=="state1") {
echo 'document.getElementById("button1").disabled = true;';
}
else if($state=="state2") {
echo 'document.getElementById("button2").disabled = true;';
}
?>
}
</script>
I call the enableButtons() function when loading the page by using
<body onload="enableButtons()">
The php code above is just an example, the number of states and buttons is higher, that's why I would like to use this solution.
The common thing to do is to have php read the settings file, and echo the "disabled" attribute on the buttons before sending the output to the user browser. You can get more info about the attribute here here.
You do not need javascript.
Do something like this:
<button type="button" <?php if($state === 'state1') echo 'disabled'; ?>>Button text</button>
Usually you send to the client the buttons already disabled and use js to respond to any event that happens after sending the page, like selecting a combo box value..
You can omit the code, using an if sentence, or hide them using css. First approach is preferred.
Script
<script>
function isValid(f){
if(f.test.value==''){
alert('please enter name');
return false;
}else{
$(".bbutton").html("Processing please wait");
return true;
}
}
</script>
HTML
<form method="post" onsubmit="return isValid(this);">
<input type="hidden" name="te">
<input type="text" name="test">
<div class="bbutton">
<input type="submit" value="send">
</div>
</form>
When you submit the form then it will automatically hide the submit button to avoid pressing again and again, and you can redirect it to other page. May be this idea helpful.

Submitting a form and closing the window - the correct way to do it?

I am trying to submit a simple form that is in a pop-up dialog and then close the dialog.
The best article I've seen is Submit a form in a popup, and then close the popup but it seems to work intermittently for me. The page launched by the form is a PHP page that modifies a record in the database. I thought that once the request is sent the PHP page will execute, even if the launching window is closed. Apparently not though. Sometimes the table is updated, sometimes it isn't. It seems like if the SQL operation isn't fast enough the page will be closed and the process is killed.
Here's the code:
<form id="xlationform" action="updatexlation.php" method="post" onsubmit="return closeForm(this);">
Source: <br>
<textarea disabled name="sterm" rows=10 cols=50><?php echo $source ?></textarea><br><br>
Translation: <br>
<textarea name="xlt" rows=10 cols=50><?php echo $xlation ?></textarea><br><br>
<input type="hidden" name="id" value="<?php echo $termid ?>">
<input type="submit" value="Update">
</form>
<script>
function closeForm(f) {
f.submit();
window.close();
}
</script>
What's the best way of working this out? I want the window to be closed but the DB operation needs to complete first and I don't want to query the DB again if possible. Thanks for your help.
Do it in updatexlation.php like :
$e = mysqli_query(...) if ($e) { echo "<script>window.close();</script>"; }
But as mentioned above, avoid using popups.
The response page should simply have window.close in the onload event.

Variable Transfer: Web Form that connects with PHP to Database

Hello and thank you for viewing my question. I am a complete beginner and am looking for simple ways to do the following...
What I have in seperate linked documents:
HTML, CSS, Javascript, PHP
What I am having trouble with:
I need to use something like JSON (although I would also accept XML requests or Ajax at this point if they work) to transfer variables from Javascript to PHP. I need the variables to search in a database, so they need to be literally available within PHP (not only seen on a pop-up message or something).
I have seen a LOT of different ways to do this, I have even watched tutorials on YouTube, but nothing has worked for me yet. The things I am having the biggest problem with is that when I add a submit button to my form it doesn't submit my form and I don't know why.
Form code snippet:
<form id="form" name="input" method="post" action="javascript:proofLength();">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit" onsubmit="post();">
</form>
The second to last line there doesn't work. Do I need javascript to submit the form? Because I really thought that in this case it was part of the functionality of the form just like method="post"...
The other thing is that for JSON, I have no idea what to do because my variables are determined by user input. Therefore, I cannot define them myself. They are only defined by document.getElement... and that doesn't fit the syntax of JSON.
Those are really my main problems at the moment. So if anyone could show me a simple way to get this variable transfer done, that would be amazing.
After this I will need to search/compare in my database with some php/sql (it's already connecting fine), and I need to be able to return information back to a in HTML based on what I find to be true. I saw one example, but I am not sure that was very applicable to what I am doing, so if you are able to explain how to do that, that would be great also.
Thank you very, very much.
April
You don't need ajax to submit this form. You don't even need javscript. Just do this:
<form id="form" name="input" method="post" action="mytarget.php">
<input id="userinput" name="userinput" type="text" autofocus />
<input id="submit" type="submit" value="submit" />
</form>
This will send the form data to mytarget.php (can be changed of course)
See that i have added the name attribute to your text-field in the form and i changed the type of the button to submit.
Now you can work the Data in mytarget.php like this:
<?
$username = $_POST['userinput'];
echo "Your name is: ".$username;
?>
You wanted to have a check for length in the submit. There are two ways to this:
Before the input is send (the server is not bothered)
Let the server Check the input
for 1 you will have to append a event listener, like this:
var form = document.getElementById("form");
form.addEventListener("submit", function(event){
console.log("test");
var name = form.elements['userinput'].value;
if(name.length < 3){
alert("boy your name is short!");
event.preventDefault();
}
});
Enter a name with less then 3 characters and the form will not be submitted. test here: http://jsfiddle.net/NicoO/c47cr/
Test it Serverside
In your mytarget.php:
<?
$username = $_POST['userinput'];
if(strlen($username) > 3)
echo "Your name is: ".$username;
else
echo "your name was too short!";
?>
You may also do all this with ajax. You will find a lot of good content here. But I'd recommend a framework like jQuery to do so.
The problem is in this line
<form id="form" name="input" method="post" action="javascript:proofLength();">
The action should be a PHP page (or any other type of server script) that will process the form.
Or the proofLength function must call submit() on the form
In the php page you can obtain variable values using $_GET["name"] or $_POST["name"]
To summarize; your code should look like this
<form id="form" name="input" method="post" action="yourpage.php">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit">
</form>
and for your php page:
<?php
$userinput = $_POST["userinput"];
//Do what ever you need here
?>
If you want to do something in your javascript before submitting the form, refer to this answer

How do I process forms (front and back end) on the same page?

I currently have a form that looks like this (using Bootstrap):
I've traditionally processed the form via post to another php file like so
<form action="complete.php" method="post" class="form-inline" role="form">
However, it kind of ruins the user experience when they're taken to a different page, and I've seen something before, where after submitting a form, the text just changed if it was valid. So, the text and form of the above image might just be replaced with "Thank you, your email has been accepted" if they offer a valid email.
So this question is two-part:
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
Second, how do I do this on the front end? Is there a common reference term for this kind of action in JS?
Answering either part of this (both if you can!) would be wonderful. If you have reference documents for me that aren't too complicated (I'm new to this), I'd be more than happy to read them too.
Thank you!
I'm going to extend on what Sam Sullivan said about the Ajax method.
Ajax basically runs any script in the background, making it virtually unnoticeable to the user. Once the script runs you can return a boolean or string to check if the result is true or false.
JS:
function validateForm(){
$.ajax({
type: 'POST',
url: '/path/to/processForm.php',
data: $('#yourForm').serialize(),
success: function(output){
if(output){ // You can do whatever JS action you want in here
alert(output);
}else{
return true; // this will redirect you to the action defined in your form tag, since no output was found.
}
}
});
return false;
}
Then in your processForm.php script, you validate the data through $_POST. Whatever you echo out in this script, will be your output.
For more, http://api.jquery.com/jquery.ajax/
Either include the PHP and form logic on the same page:
<?php
if(isset($_POST['submit'])) {
// Submit logic
echo 'Success';
}
?>
<form action="" method="POST">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
Or you can submit it with AJAX:
<form action="" method="POST" onsubmit="submitForm(this); return false;">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
function submitForm(form)
{
// This can use AJAX to submit the values to a PHP script
}
</script>
If you have jQuery, you don't need to use an inline event handler (which is better):
<script type="text/javascript">
$('form').submit(function(event) {
event.preventDefault();
$form = $(event.target);
// AJAX here
});
</script>
This should be enough to get started..let me know if you have specific questions.
Change the form to
<form action="[whatever the page name is]" method="post" class="form-inline" role="form">
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
At the top of the page, add
<?php
if(isset($_POST)){
// Check for the $_POST variables and process
// $content = "<div> ... </div>" // Then echo out the content in place of the original for
}
?>
You can just put form action="filename-of-the-form-processor" or leave it blank for same page. If you can't avoid to put php module on the same page where your form reside make a view.php file then just include it.
index.php <- where form process happends
index.view.php <- where form tags reside so you will have a cleaner line of codes.
Note: this is not the best way to do it.

Categories

Resources