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
Related
I have a problem in automating a form with hidden inputs in PHP. Basically I'm doing an input for a barcode scanner where the user will input the barcode and it will auto-submit, just like in a cash registry.
The conflict which I think is the cause of the problem is because of a conditional form. Here is a snippet:
<form method="post" id="form1">
<div class="products">
<input type="text" name="code" class="form-control" autofocus required onchange="submit()" />
</div>
</form>
<?php
$query = 'SELECT * FROM product WHERE PRODUCT_CODE='.$code.' GROUP BY PRODUCT_CODE ORDER by PRODUCT_CODE ASC';
$result = mysqli_query($db, $query);
if ($result):
if(mysqli_num_rows($result)>0):
while($product = mysqli_fetch_assoc($result)):
?>
<form id="form2" method="post" action="pos.php?action=add&id=<?php echo $product['PRODUCT_CODE']; ?>" >
<input type="hidden" name="quantity" class="form-control" value="1" />
<input type="hidden" name="name" value="<?php echo $product['NAME']; ?>" />
<input type="hidden" name="price" value="<?php echo $product['PRICE']; ?>" />
<input type="submit" name="addpos" style="margin-top:5px;width: 462px" class="btn btn-info" value="Add"/>
</form>
<?php
endwhile;
endif;
endif;
?>
<script>
function submit() {
document.getElementById("form1").submit();
}
document.getElementById("form2").submit();
</script>
The data from form1 has no trouble auto-submitting, then the form2 will auto-submit but nothing happens. I need help on how can I make form2 auto-submit correctly too. I have tried different event handling for form2 but nothing happens. I only know a little bit of javascript so that's just how my script turned out.
Thank you, Programming kings!
Because the second form is inside the while loop, if there are multiple results there will be multiple forms with the same id = "form2".
You need an increment variable $incrm = 2 inside the loop,
form id='form<?php echo $incrm;?>',
with $incrm++ before ending it. I also recommend to add ann onchange event to the last input 'price' ; onchange = submit(this).
function submit(inp) {
inp.parentElement.submit();
}
I am having trouble passing a value
when pressing this button(the code for the button down below).
<div class="timeline-footer">
<button class="btn btn-primary btn-xs" name="onderreact_btn" type="submit">Reageer</button>
</div>
It needs to give a <form> a id from that reaction.
the code for the form to save it in the db. this works just fine but now it needs to give the id from the reaction when pressing the button to this form.
<?php
if(isset($_POST['react_btn'])){
unset($q1);
$q1['reactie'] = $app->check_string($_POST['reactie']);
$q1['topic_id'] = $app->check_string($_POST['topicid']);
$q1['klant_id'] = $app->check_string($_POST['klantid']);
$q1['ledenpagina_id'] = $app->check_string($_POST['ledenpaginaid']);
$app->insert_query('reacties', $q1, 'id');
}
?>
<form action="" method="post">
<div class="form-group">
<label for="comment">Reactie:</label>
<textarea class="form-control" name="reactie" rows="3" id="comment"></textarea>
<input type="hidden" name="klantid" value="<?php echo $_SESSION["klant_id"] ?>">
<input type="hidden" name="topicid" value="<?php echo $actieftopicid ?>"
<input type="hidden" name="ledenpaginaid" value="<?php echo $_SESSION["ledenpagina_id"]; ?>">
<input type="hidden" name="onderreactieID" value="<?php echo $reactie; ?>">
<button type="submit" name="react_btn" class="btn btn-primary">Plaats reactie</button>
</div>
</form>
I think I need to make a hidden input where I post the reactionID in and make some kind of javascript variable with a default set to 0 and when pressing on a button it needs to give that value trough to this variable
If you just need a test, if the button was pressed, check if the button was submittd:
if (isset($_POST['react_btn')) {
// ...
}
But as the value of the button is it's text, you should also add an hidden field, storing your id.
Keep in mind, that you could also submit the form by pressing enter inside a textfield in the form - in this case, the button wasn't pressed!
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!");
}
});
}
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>
I have a form that has a text field that is a required entry for one(1) of my two(2) buttons. The first(1st) button applies a code, in the text field, to the products in the cart section of my store. The second(2nd) removes all codes from all products in the cart section.
What's the best way of going about this?
Thx.
<div id="cart-coupon-menu" class="coupon-menu-hide">
<form id="discount-coupon-form" action="<?php echo $this->getUrl('checkout/cart/couponPost') ?>" method="post">
<div class="discount">
<div class="discount-form">
<input type="hidden" name="remove" id="remove-coupone" value="0" />
<div class="input-box">
<input class="input-text" id="coupon_code" name="coupon_code" value="<?php echo $this->escapeHtml($this->getCouponCode()) ?>" placeholder="Enter a Coupon or Promo Code" autocomplete="off"/>
</div>
<div class="buttons-set">
<button type="button" title="<?php echo $this->__('Apply Coupon') ?>" class="button" onclick="discountForm.submit(false)" value="<?php echo $this->__('Apply Coupon') ?>"><span><span><?php echo $this->__('Apply Coupon') ?></span></span></button>
<button type="button" title="<?php echo $this->__('Cancel Coupon') ?>" class="button" onclick="discountForm.submit(true)" value="<?php echo $this->__('Cancel Coupon') ?>"><span><span><?php echo $this->__('Cancel Coupon') ?></span></span></button>
</div>
</div>
</div>
</form>
</div>
The above form will be serialized and set to a controller via AJAX and an appropriate response will be returned.
When the input box is null I want the input box to act as a required field and disallow submission via the first button. However, when it is null the second button should still allow for submission. When text is entered into the input box they both behave normally.
Currently i'm attempting to do something like this:
<script type="text/javascript">
//<![CDATA[
var discountForm = new VarienForm('discount-coupon-form');
discountForm.submit = function (isRemove) {
if (isRemove) {
$('coupon_code').removeClassName('required-entry');
$('remove-coupone').value = "1";
} else {
$('coupon_code').addClassName('required-entry');
$('remove-coupone').value = "0";
}
if(something where I identify if it is required and the field is null){return null;}
else{continue with ajax call;}
I think it's just a simple javascript something like:
<button type="button" title="<?php echo $this->__('Apply Coupon') ?>" class="button" onclick="isValid() ? discountForm.submit(false) : handleInvalid()" value="<?php echo $this->__('Apply Coupon') ?>"><span><span><?php echo $this->__('Apply Coupon') ?></span></span></button>
I used a ternary operator in there... so basically it says if isValid() returns true, execute: discountForm.submit(false) otherwise execute: handleInvalid().
Then the javascript functions would be:
function isValid() {
var couponCode = document.getElementById('coupon_code').value;
return /* whatever logic you want here... */
}
function handleInvalid() {
// do whatever you want to the coupon_code input to indicate it's required and pop up an error message
alert("Please enter a coupon code!");
}
You should give knockout a try. It updates your view(html) according to changes in your js code. See this example.