i have tried below code to execute validation function and the data insertion operation the followed code runs correctly on chrome but firefox not showing the message of succesfully insertion..
<input type="submit" onclick="chk()";/>//chk() contains validations
<?
php
if(isset($_POST["submit"]))
{
data insertion code
if(true)
{
<script language="javascript">alert " Adverties added";window.location="adverties.php";</script>
}
}
?>
Put JS in echo:
echo '.. script ... JS code';
I don't know if it's stackoverflow mistake, but " Adv.. " text is not in ( )
So it should be:
if(true)
{
echo '<script language="javascript">alert(" Adverties added");window.location="adverties.php";</script>';
}
I think I got it working.
<form action="[name of the page]" method="post">
<input name="submit" type="submit" onclick="chk()"/>
</form>
<?php
if(isset($_POST["submit"])){
if(true){
echo'<script> alert("Adverties added");window.location = "adverties.php";</script >';
}
}
?>
so I put the <input> inside a <form> that redirects you to the current page and used the POST method.
You also have to use the name property inside of the input tag inorder for $_POST["submit"] to work, I also added the echo to print the JavaScript correctly.
I hope this solves your problems.
p.s. sorry for my bad enlish :)
Related
I have made a simple form and php script which should read a variable from the html form text box and when the user clicks submit a simple message will be displayed saying 'You are searching for songs by artist_name' but when i try i get either a blank page or a message saying undefined. however if i just echo the php variable it displays the value correctly.
i have tried to just use
alert($artist_name) and alert('$artist_name')
But i get Uncaught ReferenceError: $artist_name is not defined. or the alert displays '$artist_name' instead of the value ?
However something like
<?php echo $_GET["artist"]; ?>
successfully get the text ???
and this works ok too.
elseif ($artist_name =="foo") { ?>
<script language="javascript" type="text/javascript">
alert("you enetered foo");
window.location = 'index.html';
</script>
<?php
}
so it is getting the variable ok but i just cant seem to include it in my alert message which is the entire aim of this code, Please can someone show me what i am doing wrong. Many thanks.
my code below:
the html
<form id="form1" action="searchresults.php" method="GET">
<div id="artform">
<fieldset>
<legend> Search for music </legend>
<p> <label> Artist (*): </label> <input type="text" name="artist" id="artist" placeholder="enter an artists" class="add1"></p>
</fieldset>
<input type="submit" class="button1">
<input type="reset" class="button2">
</div>
</form>
the php
<?php
$artist_name = $_GET['artist'];
if (empty($artist_name)) { ?>
<script language="javascript" type="text/javascript">
alert('Field blank !, please try again.');
window.location = 'index.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('You are searching for songs by' $artist_name); // the issue is here
window.location = 'index.html';
</script>
<?php
}
?>
You forgot to enclose $artist_name with PHP start and end tag.
alert('You are searching for songs by' $artist_name); // the issue is here
Should've been:
alert('You are searching for songs by <?php echo $artist_name; ?>'); // the issue is here
thank you i got it working, Kek i tried your method but i got an error uncaught SyntaxError: missing ) after argument list, But 125248 comment worked perfectly, i had to include the tags for it to work. Thank you for your time.
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";
}
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.
I've been trying to integrate ckeditor in my php website, and I've encountered the following issue.
Essentially, the content in ckeditor wouldn't appear in the $_POST variable after submitting the form.
I looked the issue up and apparently one has to update the form field with a small piece of code.
So I wrote the corresponding script and linked it to the submit button in order to get the result I want, but $_POST still shows up as empty.
I'm inexperienced with Javascript so the error probably lies there. Any ideas?
cktest.php:
<!DOCTYPE html>
<html>
<head>
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="http://localhost/ECLIPSEPHP/ckeditor/ckeditor.js"></script>
</head>
<body>
<form action = <?php echo $_SERVER['PHP_SELF']
?>>
<textarea name="test" id="test" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<input type = "submit" name = 'submitButton' id = 'submitButton' value = 'Submit'>
<script>
// Replace the <textarea id="test"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'test' );
</script>
<script type = "text/javascript" src = "http://localhost/ECLIPSEPHP/js/update.js"></script>
</form>
</body>
</html>
<?php
var_dump($_POST);
//echo $_POST['test'];
?>
The javascript supposed to handle the onclick event :
function updateAllMessageForms()
{
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
}
var submitButton = document.getElementById('submitButton');
submitButton.onclick = updateAllMessageForms;
There are quite a lot of problems with that code. The first thing to check is to add a method to that form tag: method="post".
See what <form action = <?php echo $_SERVER['PHP_SELF'] ?>> renders. It looks like it could be a wrong. I'm guessing it should be more like <form action="<?php echo $_SERVER['PHP_SELF'] ?>">.
Don't use ' for HTML attribute delimiters, use " instead: 'submitButton' --> "submitButton".
If you edit the updateElement a little: CKEDITOR.instances[instance].updateElement(); alert(1); - do you see the alert? If not, that code is not being called and you need to edit it so that it is.
Don't add spaces between your attribute name, the equals symbol and the value. That looks very strange and could be interpreted wrong or it could send Internet Explorer into quirks mode. Try to change this style: type = "submit" to type="submit" and keep up with that style.
Remember that it's often a good idea to look at the Rendered source in the browser to see what the browser actually gets. Happy coding!
I am printing a very simple JavaScript using PHP, which doesn't get executed. If I print the data, I see the following script (exactly as needed) at the end of the HTML file:
<script type="text/javascript">
document.getElementById("message").innerText="Email already exists";
</script>
I have also tried using innerHTML="Email already exists";.
This is printed in PHP as such:
echo "<script type=\"text/javascript\">
document.getElementById(\"message\").innerText=\"Email already exists\";
</script> ";
In my HTML I have an element which has the ID: message. It looks like this:
<h3 id="message"> </h3>
What I am expecting is to get "Email already exists" in the h3, however this doesn't happen. The JavaScript is not executed. If I use the exact same JavaScript code but place it ahead or on an "onclick" request, the code works.
One thing which could be relevant: I noticed that the JavaScript is printed after the closing HTML tag.
How do i get the JavaScript code to execute after being echo'ed into the HTML? I've read several threads which said its supposed to simply run, however mine doesn't. I have tried about 50 different fixes, none of which worked.
The code: http://ideone.com/dmR42O
You mentioned this:
One thing which could be relevant. I noticed that the javascript is
printed AFTER the closing html tag (the ).
That is very relevant. Any Javascript must be contained within the <html> element (before </html>). But, be sure that the Javascript appears after the <h3>. Javascript will run when it's encountered, as Marc said in a comment above.
If the Javascript must be before the , then do this:
window.onload=function(){
document.getElementById("message").innerText="Email already exists";
};
Try it like this:
echo '<h3 id="message"> Email already exists!</h3>';
<!DOCTYPE html>
<html>
<body>
<form id="submitform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="logIn_email_input" name="email" type="text" placeholder="Enter e-mail address" autocomplete="off">
<input id="logIn_password_input" name="password" type="password" placeholder="Enter password" autocomplete="off">
<input id="logIn_submit" type="submit" name="logIn_submit">SIGN UP</button>
</form>
<?php
$query = mysql_query("SELECT userid FROM users WHERE email = '". $email ."'");
if (mysql_num_rows($query) > 0) {
echo '<h3 id="message"> Email already exists!</h3>';
}
?>
<body>
</html>
You had a lot of issue here (maybe typos ?)
action="<?php echo $PHP_SELF;?>" should be action="<?php echo $_SERVER['PHP_SELF']; ?>"
<button id="logIn_submit" should be <input id="logIn_submit" type="submit" name="logIn_submit">
<? php had extra space should be <?php
If statement was missing closing brace }
No <body> tags