submit button post not sent after using javascript - javascript

I have 3 separate forms each with their own submit buttons (removed all other lines of form code as not required):
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicSub" id="postingTopicSub" enctype="multipart/form-data">
<input type="button" name="submittopic" id="submittopic" value="Submit" onclick="topicPostSubmit();"/>
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicReply" id="postingTopicReply" enctype="multipart/form-data">
<input type="button" name="submitreply" id="submitreply" value="Submit" onclick="replyPostSubmit();"/>
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicEdit" id="postingTopicEdit" enctype="multipart/form-data">
<input type="button" name="submitedit" id="submitedit" value="Submit" onclick="editPostSubmit();"/>
I am using Javascript to verify the form data is filled in before submitting however because using JavaScript the POST data from the button is not being sent.
JavaScript submit for each form:
document.getElementById("postingTopicSub").submit();
document.getElementById("postingTopicReply").submit();
document.getElementById("postingTopicEdit").submit();
On my data page I use isset to make the SQL queries run are for the correct form:
// User meets all conditions and posts a topic
if (isset($_POST['topicID'], $_POST['subject'], $_POST['post_text'], $_SESSION['username'], $_POST['submittopic']) && !isset($_POST['forumID'])) {
// User meets all conditions and posts a reply
if (isset($_POST['topicID'], $_POST['post_text'], $_SESSION['username'], $_POST['submitreply'], $_POST['forumID'], $_POST['subject'])) {
// User meets all conditions and edits a post
if (isset($_POST['topicID'], $_POST['post_text'], $_SESSION['username'], $_POST['submitedit'], $_POST['forumID'], $_POST['postID'], $_POST['subject'])) {
My questions:
Is there a way to keep my method of keeping the 3 SQL queries separate
to the specific forms
Is there a way to sent the POST of the submit even though it is being
submitted through JavaScript?
Is there another way that I just haven't seen.
Thanks in advance.
EDIT:
Full form (without bbcodes)
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicSub" id="postingTopicSub" enctype="multipart/form-data">
<input type="hidden" name="topicID" id="topicID" value="<?php echo $topicID ?>"/>
<div class="post-subject">
Subject:
<input type="text" name="subject" id="subject" />
</div>
<div class="post-textarea">
<textarea name="post_text" id="post_text" cols="100" rows="30"></textarea>
</div>
<div class="post-button">
<input type="button" name="submittopic" id="submittopic" value="Submit" onclick="topicPostSubmit();"/>
</div>
</form>
Full JS for form validation:
function forumssubmit()
{
var subject = document.getElementById("subject").value;
var text = document.getElementById("post_text").value;
if(subject=="" || text=="")
{
alert('Please fill in the subject and text');
return false;
}
return true;
}
function topicPostSubmit()
{
if(forumssubmit())
{
document.getElementById("postingTopicSub").submit();
}
}
EDIT2::
New js:
function forumssubmit()
{
var subject = document.getElementById("subject").value;
var text = document.getElementById("post_text").value;
if(subject=="" || text=="")
{
alert('Please fill in the subject and text');
return false;
}
return true;
}
function topicPostSubmit()
{
if(forumssubmit())
{
//document.getElementById("postingTopicSub").submit();
return true;
}
}
New button:
<input type="button" name="submittopic" id="submittopic" value="Submit" onclick="return topicPostSubmit();"/>

If you're really just "using Javascript to verify the form data is filled" you can add a return to the onclick's of your submit buttons. You'll then be able to use those for submitting the form instead of Javascript.
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicSub" id="postingTopicSub" enctype="multipart/form-data">
<input type="submit" name="submittopic" id="submittopic" value="Submit" onclick="return topicPostSubmit()"/>
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicReply" id="postingTopicReply" enctype="multipart/form-data">
<input type="submit" name="submitreply" id="submitreply" value="Submit" onclick="return replyPostSubmit()"/>
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicEdit" id="postingTopicEdit" enctype="multipart/form-data">
<input type="submit" name="submitedit" id="submitedit" value="Submit" onclick="return editPostSubmit()"/>
Then in the javascript if you have a bad state return false.
function editPostSubmit(){
if(data == 'bad')
return false;
return true;
}
I also want to make sure you're doing data validation on the backend. We don't want to allow SQL injection on your page.
Edit:
Updated your modified code.
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicSub" id="postingTopicSub" enctype="multipart/form-data">
<input type="hidden" name="topicID" id="topicID" value="<?php echo $topicID ?>"/>
<div class="post-subject">
Subject:
<input type="text" name="subject" id="subject" />
</div>
<div class="post-textarea">
<textarea name="post_text" id="post_text" cols="100" rows="30"></textarea>
</div>
<div class="post-button">
<input type="submit" name="submittopic" id="submittopic" value="Submit" onclick="return forumssubmit();"/>
</div>
</form>

Related

Could not validate the form input fields using PHP and JavaScript

I am facing an issue while validating the input fields inside the form using PHP and JavaScript. I am providing my code below.
<form autocomplete="off" action="<?php echo base_url() . $tourModule; ?>/search" method="GET" role="search" onSubmit="return checkform();">
<input type="text" data-module="<?php echo $module; ?>" class="hotelsearch locationlist<?php echo $tourModule; ?>" placeholder="Tourist Destination" value="<?php echo $_GET['txtSearch']; ?>">
<input type="hidden" id="txtsearch" name="txtSearch" value="<?php echo $_GET['txtSearch']; ?>">
<div class="col-md-12 form-group go-right colspecing col-xs-12 submit text-center">
<button type="submit" class="btn btn-lg pfb0 loader">
<?php echo trans( '012'); ?> </button>
</div>
</form>
<script type="text/javascript">
function checkform(){
console.log('validate form');
var textname=document.getElementById('txtsearch');
if (textname.value=='' || textname.value==null) {
alret('Please select Tourist Destination.');
return false;
}else{
return true;
}
}
</script>
Here I need before submit the form the input field will validate but in my case when I am clicking on submit button checkform function is not executing at all. I need to check that validation.
There is a typo in your code. Change alret to alert

PHP Prevent Re submission for multiple forms on same page

Hi have checked answer from this page: But it uses action="" is it vulnerable to XSS attacks? If yes then without such solution what are my options?
I tried using header redirect. But as I have 2 forms,(in some pages 4-5 forms) header re direction is not working for me with errors.
Here is my code: (Simplified)
1st form: works ok with a redirect.
<form name="ip_block" method="post" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="ip"> Enter IP:</label>
<div class="col-sm-8">
<input type="text" name="ip" class="form-control" id="ip" />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="submit" class="btn btn-default"
name="ip_block_add">Submit</button>
</div></div>
</form>
<?php
if(isset($_POST['ip'])){
if($IP = filter_input(INPUT_POST, 'ip',
FILTER_SANITIZE_STRING)){
$add_ip = $mysqli->prepare("INSERT INTO block_ip(b_ip)
VALUES(?)");
$add_ip->bind_param("s",$IP);
$add_ip->execute();
$add_ip->store_result();
$add_ip->close();
header("refresh:5;url=./admin-security.php");// avoiding form
resubmission
echo 'Added successfully';
}
else {
echo 'failed to insert';
}
}
?>
Form 2:
<form name="clear_data" method="post">
<input type="hidden" name="data_clear" value="1"/>
<button type="submit" class="btn btn-warning">Clean Data</button>
</form>
<?php
if(isset($_POST['data_clear'])){
if($mysqli->query("CALL clear_old_data")){
header("refresh:5;url=./admin-security.php");// avoiding form resubmission
echo 'operation successfull';
}
else
{
echo 'database failure';
}
}
//----
?>
For Second form I get error like this
Warning: Cannot modify header information - headers already sent by
For 2nd form I am using header before echo still it doesn't work.
reference, I tried with javascript too but that failed.
echo "<script>setTimeout('window.location.href='./admin-
security.php';',4000);</script>";
Updated with Dainis Abols idea: but form re submit option is still showing on page refresh
<form name="clear_data" method="post">
<input type="hidden" name="data_clear" value="1"/>
<?php
$var=111;
$_SESSION['var']=$var;
?>
<input type="hidden" value="<?php echo $var; ?>" name="varcheck"
/>
<button type="submit" class="btn btn-warning">Clean
Data</button>
</form>
<?php
if(isset($_POST['data_clear']) &&
($_POST['varcheck']==$_SESSION['var'])){
// Some code
}
I'd rather use ajax to send data to the database, without form submiting, and on success I would use js to redirect to /admin-security.php. In this case it's not possible to send the data twice.
Here is the PHP Code:
<?php
if(isset($_POST['ip'])){
if($IP = filter_input(INPUT_POST, 'ip',
FILTER_SANITIZE_STRING)){
$add_ip = $mysqli->prepare("INSERT INTO block_ip(b_ip)
VALUES(?)");
$add_ip->bind_param("s",$IP);
$add_ip->execute();
$add_ip->store_result();
$add_ip->close();
echo 1;
}
else {
echo 0;
}
exit;
}
?>
HTML:
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="ip"> Enter IP:</label>
<div class="col-sm-8">
<input type="text" name="ip" class="form-control" id="ip" />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="button" onClick="send_form()" class="btn btn-default"
>Submit</button>
</div></div>
</div>
And AJAX written with JQuery
<script>
function send_form() {
$.ajax({
url: "./admin-security.php",
type: "POST",
data: {
ip: $("#ip").val()
},
success: function(response) {
if(response==1) {
alert("Done");
location.href = "./admin-security.php";
}
else alert("Fail!");
}
});
}

submitting content to a .txt using php and staying on the same page and not go to the php page

I wanna submit/write content to a .txt file and i have to used php to do it, but i don't wanna open the php page and wanna stay on the same page.
How can I do this?
Index.html
<form action="writer.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
writer.php
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "|| \n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo " written to file";
}
}
else {
die('no post data to process');
}
?>`
You could simply use iframes, easier alternative to AJAX.
<iframe name="panel" style="display:none;"></iframe>
<form action="writer.php" method="POST" target="panel">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
...and as everyone here is yelling, consider learning AJAX.
create a php file with following in it.
<?php
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
file_put_contents('mydata.txt', $input, FILE_APPEND | LOCK_EX);
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php if(isset($message)) echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>

Trying to validate a form client and server side

The client side validation looks something like this:
function validateFname() {
var x = document.getElementById('fname').value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
The server side below it:
if(isset($_POST['SubmitForm'])){
if(empty($_POST['fname'])){
echo "First name cannot be empty!<br/><br/>";
return false;
}
and the form itself below that:
<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>"
accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname" onsubmit="return validateFname()"
class="required" value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" value="Send"/>
Ofcourse there is a lot more to it but ive just given one example above. I am trying to figure out why the (clientside)javascript function is not working and instead the (server) php error is coming up. I need to be able to have the client run validation checks before the server to reduce load.
The onsubmit is a event that belongs to the <form> element. You have placed it with the submit button which won't work.
Here's a working fiddle:
Demo
Reference
<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>" accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname" value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" onClick="return validateFname()" value="Send"/>
</form>
try the above code. Instead of using onSubmit in input text field use onClick in submit button.
good luck

How to show box after submit value in form

So I have pop-up window where user need to enter name, after clicking submit button this window close.
You can test it here: http://eurokos.lt/under20/button.php (Click 21 button, then try to enter any value and see what happens)
For this pop-up box I've used function:
function popUp() {
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
}
This function is used for X button to close window:
function closeWindow() {
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none';
}
My button which open pop-up window looks like:
Echo "<input type='button' onclick='popUp();' value='".$i."' />";
And here is PHP_SELF and form:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "</br>You have entered: <b> $name </b>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
`
What I need to do that posted result what entered and window not closed?
Maybe I need to use popUp() function again when submitting? But how to do that correctly? Thank you.
Try this:
html:
<form method="post" action="" onsubmit="return display()">
<div id="answer"></div>
<input type="text" name="name" id="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
javascript:
function display(){
var ans = document.getElementById("name").value
document.getElementById("answer").innerHTML="You have entered:"+ans;
return false;
}
Update:
function popUp(){
document.getElementById("answer").innerHTML=""; //Add these in your popup function
document.getElementById("name").value="";
}
First of all i suggest you to avoid PHP_SELF in the action it can be manipulated by people and it's not good.
at top of page try to do :
<?php
$thispage = $_SERVER['PHP_SELF'];
?>
<html>
.
.
.
<form method="post" action="<?=$thispage?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
</html>
Then, using the action for sending data to PHP, will reload the page so you are probabilly losing all the inline fix you did.
Try to get the input values after the submit, assign them to varibles and do, for example:
xmlhttp.open("POST","<?=$thispage?>",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=name");
with an asynchronous call you don't reload the page and you don't lost your changes

Categories