Here I'm working on a simple withrawal page where users can select the amount they want to withdraw and submit afterwhich a bootstrap modal pops up confirming to the user that the request has been sent whilst updating the section in the db with the amount selected.
So far im facing no issues when user selects the amount and click on submit, the modal pops up but unfortunately the database is not updated, I can't fathom where i'm getting it wrong.
Here is the Php
<?php
// Define variables and initialize with empty values
$withraw = "";
$withraw_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate Withrawal
if(empty(trim($_POST["withraw"]))){
$withraw_err = "Please Choose a Amount.";
} else{
$withraw = trim($_POST["withraw"]);
}
// Check input errors before inserting in database
if(empty($withraw_err)){
// Prepare an insert statement
$sql = "UPDATE users SET withraw = (?) WHERE id = ".$id;
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_withraw);
// Set parameters
$param_withraw = $withraw;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
echo "";
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
Here is the code for the form im using.
<form onsubmit="openModal()" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" id="myForm" >
<div class="form-group <?php echo (!empty($withraw_err)) ? 'has-error' : ''; ?>">
<div style='width:50%;' class='selectt'><select name="withraw" class="form-control" value="<?php echo $withraw; ?>"><option >Choose Amount</option>
<option value="500">500</option>
<option value="1000">1,000</option>
<option value="1500">1,500</option>
<option value="2000">2,000</option>
<option value="2500">2,500</option>
<option value="3000">3,000</option>
<option value="3500">3,500</option>
</select>
</div>
<span class="help-block"><?php echo $withraw_err; ?></span>
</div>
<div class="form-group" >
<button type="submit" class="btn btn-info btn-lg" value="Submit">
Withraw <i class="fa fa-check-circle"></i> </button>
<button type="reset" class="btn btn-default" value="Reset"><i class="fas fa-redo"></i> Reset </button>
</div>
</form>
And I've added some javascript to load the bootstrap modal after the form is Submitted
<script>$('#myForm').on('submit', function(e){
e.preventDefault();
$('#myModal').modal('show');
});</script>
Here is where I'm completely lost as, when I remove the e.preventDefault() the form Updates the database row called withraw but the bootstrap does not load at all and I've been trying to set so that the bootstrap loads and the database row is updated as well I do not have more knowledge on how to tackle this situation as I read similar questions and some suggestions are to use Ajax but I have limited knowledge on how to do that.
I didn't post the bootstrap because i don't see it necessarily its a normal Bootstrap modal setup
Related
Here's my code. Now here what happens is when I fill that specific form with just 1 input the data gets submitted and the alert is shown after that, but if I don't fill anything in the form and just click on submit button, the alert is shown even if the form is empty, and after the alert, it shows that please fill out this field.. so what went wrong? tried searching for this solution and tried so many things but nothing works... :(
<div class="newsletter">
<p>Sign Up for the <strong>NEWSLETTER</strong></p>
<form method="post">
<?php
if(isset($_POST['subscribe']))
{
$e_mail = $_POST['e_mail'];
$conn = new mysqli('localhost','root','','purrfect_whiskers');
if($conn->connect_error)
{
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
}
else
{
$stmt = $conn->prepare("insert into newsletter(e_mail) values(?)");
$stmt->bind_param("s", $e_mail);
$stmt->execute();
$stmt->close();
$conn->close();
}
}
?>
<input class="input" type="email" name="e_mail" text-transform="lowercase" placeholder="Enter Your Email" autocomplete="off" required="required">
<button class="subscribe" onclick="submit_email()" type="submit" name="subscribe"><i class="fa fa-envelope"></i> Subscribe</button>
<script type="text/javascript">function submit_email(){alert("You've been subscribed to our newsletter!");}</script>
</form>
</div>
It looks like you should validate that the user did put in a value for email before allowing the submission. If they did not, present an error. If they did, allow the submission and on page refresh, present the success alert
There are a couple ways to prevent automatic form submission, one of them is to put an onsubmit handler in the form tag and have it return true (to allow the submission or false to prevent it. You can do all your validating in that handler:
<form method="POST" onsubmit="return submit_email()">
Then in your function, check that the value is there before allowing it to continue:
<script type="text/javascript">
function submit_email(){
let email_input = document.querySelector("input[name='e_mail']");
if (email_input.value=="") {
alert("Please type in your email first");
return false; // this prevents the form from submitting
}
return true; // this allows the submission
}
</script>
The form will submit, the page will refresh and your PHP code will do it's thing. At the end of which, just hardcode your alert, like this:
<?php
if(isset($_POST['subscribe'])){
// do all your code as you are, then end with:
?>
<script>
alert("You've been subscribed to our newsletter!");
</script>
<?php
}
?>
The alert code executes no matter what. You must therefore display it only if there is nothing in your form.
For that, I added an id in your input and I made a check to know if your form is empty or not.
The best would be to check with regex if it is indeed an email address but here is the code just to verify if it is just not empty
Here is the code:
<div class="newsletter">
<p>Sign Up for the <strong>NEWSLETTER</strong></p>
<form method="post">
<?php
if(isset($_POST['subscribe'])) {
$e_mail = $_POST['e_mail'];
$conn = new mysqli('localhost','root','','purrfect_whiskers');
if($conn->connect_error) {
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
} else {
$stmt = $conn->prepare("insert into newsletter(e_mail) values(?)");
$stmt->bind_param("s", $e_mail);
$stmt->execute();
$stmt->close();
$conn->close();
}
}
?>
<input id="id_input" class="input" type="email" name="e_mail" text-transform="lowercase"
placeholder="Enter Your Email"
autocomplete="off" required="required">
<button class="subscribe" onclick="submit_email()" type="submit" name="subscribe"><i class="fa fa-envelope"></i>
Subscribe
</button>
<script type="text/javascript">function submit_email() {
if (document.getElementById("id_input").value !== "") {
alert("You've been subscribed to our newsletter!");
}
}</script>
</form>
</div>
I am looking to enable only one submission of form per session. I have tried to disable submit button but this on click function is nothing for bots so extra layer of single submission per session is what i think can save somewhat from bots
OR
Create token for each submission to make submission more secure and unique
Which one is better and how to implement so any user (bots) can not submit same form twice
Code I have is
<form role="form" method='post' action='index.php' id='cme'>
<input type="hidden" name="val" value="<?php echo $val ?>" />
<fieldset>
<div class="form-group">
<center><div class="g-recaptcha" data-sitekey="sitekey"></di</center>
</div>
<div class="row">
<center>
<input type="submit" name="claim" class="btn btn-lg btn-success btn-block" value="Claim Now" id="claim" onclick="setTimeout(disableFunction, 1);">
</center>
</div>
</fieldset>
</form>
Submit section
if(isset($_POST['claim'])) {
$recaptcha = $_POST['g-recaptcha-response'];
if(!empty($recaptcha)) {
# Use the recaptcha function here
$resp = getGoogleRecaptcha();
if($resp['success']) {
header('Location: index.php');
# Capture value from the form submit
$bonval = $_POST['bonval'];
# Insert normally
$db->fetchVal("insert into log (`user_id`,`amount`) values (?,?)", array($id, $bonval));
}
}
else { ?>
<div class="overlay"><div class="popup" style="background:red;">
<h2>Opps</h2>
<a class="close" href="#">×</a><br/>
<div><center><span class="blink_me">You missed it</span></center></div>
</div></div>
<?php }
}
Now issue is form opens on popup and user keeps clicking and score keeps adding as with each click session view is +1
Can you please guide me about this issue solving so one click and only one submission
I think it can be better to do form submission through javascript so on submit function can be controlled more wisely to kill popup on more than one submit click....am i right, if yes plz guide this way
Below is one way of doing this using sessions.
Basically I am generating a token and storing it in session if its not already in session. I am also including the same in the form, which can be cross checked (in index.php) to see if it matches with the session variable or not.
<?php
if(! isset($_SESSION['cme-token']) ){
$cme_token = rand(11111, 99999);
$_SESSION['cme-token'] = $cme_token;
} ?>
<?php if (!isset($_SESSION['cme'])){ ?>
<form role="form" method='post' action='index.php' id='cme'>
<input type="hidden" name="token" value="<?php echo $cme_token ?>" />
<fieldset>
<div class="form-group">
<center><div class="g-recaptcha" data-sitekey="sitekey"></di</center>
</div>
<div class="row">
<center>
<input type="submit" name="claim" class="btn btn-lg btn-success btn-block" value="Claim Now" id="claim">
</center>
</div>
</fieldset>
</form>
<? } else {
<div>ALREADY CLAIMED!</div>
}?>
In index.php you can do additional check just to be sure that the token was not modified in between by user like below.
// INDEX.PHP
<?php
if($_POST['token'] == $_SESSION['cme-token']) {
//PROCESS THE FORM
} else {
// IGNORE THE FORM SUBMIT AS IT DOESN'T CARRY PROPER TOKEN
}
?>
I need one help. I have some multiple textarea, radio button and dropdown list which are created by clicking on a button. I need to validate them for textarea has blank value, radio button check and dropdown select using JavaScript/jQuery. I am explaining my code below.
<div style="width:24%; float:left; padding:10px;">No of questions :
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" value="<?php if($_REQUEST['edit']) { echo $getcustomerobj->no_of_question; } else { echo $_REQUEST['no_of_question']; } ?>" type="text" onkeypress="return isNumberKey(event)">
</div>
<div style="padding-bottom:10px;">
Questions : <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" onClick="addQuestionField();"><input type="button" class="btn btn-danger btn-sm" name="minus" id="minus" value="-" onClick="deleteQuestionField();">
</div>
<script>
function addQuestionField(){
var get =$("#ques").val();
if(get==null || get==''){
alert('Please add no of questions');
}else{
var counter = 0;
if (counter > 0){
return;
}else{
counter++;
<?php
$status=array("status"=>'1');
$feeddata=$db->kf_answertype->find($ustatus);
?>
<?php
$status=array("status"=>'1');
$feeddatascale=$db->kf_scale->find($ustatus);
?>
for(var i=1;i<get;i++){
$('#container').append('<div><div style="width:24%; float:left; padding:10px;"> <textarea class="form-control" name="questions'+ i +'" id="questions'+ i +'" placeholder="Questions" style="background:#FFFFFF;" rows="2"><?php if($_REQUEST['edit']) { echo $getcustomerobj->questions; } else { echo $_REQUEST['questions']; } ?></textarea></div><div style="float:left;margin-top:37px;"><div style="float:left; margin-right:10px;"><?php foreach($feeddata as $v){?> <input type="radio" name="answer_type'+i+'" id="answer_type0" onClick="selectScale(this.value,'+i+');" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?> <?php }?></div><div style="float:left; margin-top:-10px;display:none;" id="scaleid'+i+'"><select class="form-control" id="nscale'+i+'" name="noofscale'+i+'"><option value="">Select Answer Type</option><?php foreach($feeddatascale as $v){ ?><option value="<?php echo $v['_id']; ?>" <?php if($getcustomerobj->no_of_scale == $v['_id'] or $_REQUEST['no_of_scale'] == $v['_id']){ print 'selected'; } ?>><?php echo $v['noofscale']; ?></option><?php } ?></select></div><div style="clear:both;"></div></div><div style="clear:both;"></div></div>');
}
}
}
}
</script>
Here when user will click on + button some multiple textarea, radio button and dropdown list dynamically. Here I need when my form will submit I need to check the validation of all whether those are not blank/checked. Please help me.
From what I can understand from the question, I have deduced that you have a form with input controls. The user can press '+' to replicate/clone a div containing all input thus providing an additional form filled with input controls. If this is the case, you can use the following for validation to ensure that all currently visible input controls have been filled with data.
Pre-requisite: Ensure that all forms are assigned the same class name.
Example:
var visibleDivs = $(".DisplayableDiv:visible"); // .DisplayableDiv name of all class containing form controls
var hasValue = true;
// loop over all visible divs
for(i = 0; i < visibleDivs.length; ++i)
{
$(visibleDivs[i]).find('input')
.each(function() { // iterates over all input fields found
if($.trim($(this).val()).length === 0) {
hasValue = false; // if field found without value
break;
}
});
}
if(hasValue === false) {
// handle validation logic here (prompt user to complete all input areas etc)
}
There are a number of problems with your code, but in particular you have the wrong approach.
Note that after the page is rendered and the DOM displayed, PHP has finished and no more PHP can run. So how do you do more stuff in PHP? Two options:
(1) Forms, or
(2) AJAX - it's pretty easy, see these simple examples
Ajax sends specified data to a backend PHP file. Note that you cannot post AJAX data to the same file that contains the AJAX javascript. You must use a second PHP file.
The backend PHP file receives the data, uses the incoming data (e.g. num of ques) to create new HTML in a $variable and then just echos that $variable back to the originating file, where it is received in the .done() function (aka the success function), as a variable (e.g. recvd). If you receive HTML code, then that code can be injected back into the DOM via methods like .append() or .html() etc.
Here is a rough approximation of how you might proceed.
$('#plus').click(function(){
addQuestionField();
});
$('#minus').click(function(){
deleteQuestionField();
});
function addQuestionField(){
var numques = $("#ques").val();
if(numques==null || numques==''){
alert('Please add no of questions');
return false;
}
var myAj = $.ajax({
type: 'post',
url: 'ajax.php',
data: 'numques=' + numques,
});
myAj.done(function(recvd){
$('#container').append(recvd);
});
}
<style>
#d1 {width:24%; float:left; padding:10px;}
#d2 {padding-bottom:10px;}
</style>
<div id="d1" style="">No of questions :
<input id="ques" class="form-control" placeholder="no of question" type="text" />
</div>
<div id="d2">
Questions :
<input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+">
<input type="button" class="btn btn-danger btn-sm" name="minus" id="minus" value="-">
</div>
Validating user-submitted data is a separate issue, but the basic idea is shown above when the $('#ques') value is validated -- if empty, we alert a message and return false to return control to the user.
Note that you can validate either client-side (jQuery) or server-side (PHP). The difference is that when you validate client-side, you can return control to the user without losing anything they typed. When you validate server-side, you must send back all the user-typed data and re-populate the controls manually (i.e. it's a lot more work)
Also note that if you validate client side, and you have ANY concern about hacking, then you must also re-validate server side because client-side validation can be easily hacked. But if it fails server-side validation you will know the user monkeyed with your validation and you can be less kind about re-populating their entries...
Here is a basic example of client-side field validation.
I am truly a novice at coding and only succeed with trial and error. I use a WYSIWYG program to do all the main pages in my site and then add php coding to do some specified things.What I am trying to do right now is display a log in button along with a register and forgot password links to those forms, all of which I have built and working, have this display in the masterframe page when a user is not logged in and show another set of user name, profile, logout links when they are logged in. By themselves I have all these functions working, I just cant figure out how to do it this way. Any help or steering me in the right direction to teach me would be great. If you need to be paid for your help that can be arranged as well. Thank You.
update:
This is the code that I have right now and use, again I want to have the if else statement show one thing or the other on condition, and have it show in place of, all on the masterframes page.
// have this display if user is logged in
<span id="LoginName1"><?php
if (isset($_SESSION['username']))
{
echo $_SESSION['username'];
}
else
{
echo 'Not logged in';
}
?></span>
<div id="wb_Text2" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Profile</span>
</div>
<form name="logoutform" method="post" action="<?php echo basename(__FILE__); ?>" id="logoutform">
<input type="hidden" name="form_name" value="logoutform">
<a id="Logout2" href="javascript:document.logoutform.submit()">Logout</a>
</form>
//have this display if user is logged out
Log In
<div id="wb_Text3" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Register</span>
</div>
<div id="wb_Text1" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Forgot Password?</span>
</div>
I have tried doing this but I keep getting a syntax error for unexpected '<'
<span id="LoginName1"><?php
if (isset($_SESSION['username']))
{
echo $_SESSION['username'];
<div id="wb_Text2" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Profile</span>
</div>
<form name="logoutform" method="post" action="<?php echo basename(__FILE__); ?>" id="logoutform">
<input type="hidden" name="form_name" value="logoutform">
<a id="Logout2" href="javascript:document.logoutform.submit()">Logout</a>
</form>
}
else
{
Log In
<div id="wb_Text3" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Register</span>
</div>
<div id="wb_Text1" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Forgot Password?</span>
</div>
}
?></span>
<?php
// Setting a session variable when customer is logged in.
$_SESSION['user_loggedin'] = 1;
$_SESSION['customer_id'] = $customer_id; // Some reference of logged in customer
$_SESSION['customer_name'] = $customer_name; // Customer information collected from DB or other resource.
// Deciding whether to display "Login" button or Logged in status / links
if ($_SESSION['user_loggedin']) {
echo 'Hi ' . $_SESSION['customer_name'];
echo 'My Account';
} else {
echo 'Login';
echo ' Register';
echo ' Forgot Password';
}
If you have some PHP function to check whether customer is logged in or not, you can use that function like this in lieu of if ($_SESSION['user_loggedin']) condition
if (UserLoggedin()) {
// Logged in links
} else {
// Links to be displayed when customer is logged out.
}
You are mixing both PHP and HTML code. Please correct.
You have to separate / embed HTML properly in your document while using php conditions.
Example:
<?php
$condition = true;
if ($condition) {
?>
<h1>This will be displayed when condition is true</h1>
<?php
} else {
?>
<h1>This will be displayed when condition is false</h1>
<?php
} // else ends
?>
Please try this:
<span id="LoginName1"><?php
if (isset($_SESSION['username']))
{
echo $_SESSION['username'];
?>
<div id="wb_Text2" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Profile</span>
</div>
<form name="logoutform" method="post" action="<?php echo basename(__FILE__); ?>" id="logoutform">
<input type="hidden" name="form_name" value="logoutform">
<a id="Logout2" href="javascript:document.logoutform.submit()">Logout</a>
</form>
<?php
}
else
{
?>
Log In
<div id="wb_Text3" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Register</span>
</div>
<div id="wb_Text1" style="">
<span style="color:#FFFFFF;font-family:Tahoma;font-size:12px;">Forgot Password?</span>
</div>
<?php
}
?></span>
Adding some code in your question would be nice, but if I understand your question correctly you might want to try this:
$logged_in = 0;
if($logged_in == 0) {
//all the stuff you want to show when the person is not logged in
$logged_in = 1;
}
if($logged_in == 1) {
//all the stuff you want to show when the person is logged in
}
In order to do what you are trying, you need to implement just a bit of logic on the code. The example of kerv is perfectly valid. The idea is that you will validate if the user is logged in or not, before rendering the html. For example:
if($userLoggedIn){
<div> Welcome to the site </div>
} else {
<div> Your are not logged in, please do so to continue </div>
}
I'll suggest you to edit the question with some code so we can properly help you.
Create a PHP session and use that session variable for your "IF" condition boolean.
i.e. if (session active)
{then display this object}
else
{dont display this object}
Here is some documentation on PHP 5 Sessions. PHP 5 Sessions
The neat thing about PHP is that it is completely interchangeable with HTML. Therefore you and assign elements to divs. Here is an example.
<html>
<body>
<?php
$loggedInTxt="";
$loggedOutTxt="";
if (*session*){
$loggedInTxt="<div>*some html content here*</div>"
}
else{
$loggedOutTxt="<div>*some html content here*</div>"
}
?>
<?php echo($loggedInTxt)?>
<?php echo($loggedOutTxt)?>
</body>
</html>
The idea is that you test the condition within the php and create php strings containing html elements. You can insert the anywhere in your html. So if you create a button and assign the code you used to create that button to a php variable then you can echo that variable(the code for the button) anywhere in your html script. I was blown away by the implications of php. I hope this helps simplify it! (This more of an overview. Do NOT copy and paste the code)
I need to be able to when the submit button is clicked a new tab must be open
based on the anchor link coming from the database. I have been struggling for hours.
this is my form
<form action="" method="POST">
<select name="name">
<option value="">Select Names</option>
<option value="1">Names</option>
</select>
<input type ="submit" name="submit" value="find random name">
</form>
Here is the php
<?php
$query="SELECT * FROM names_table ORDER BY RAND() LIMIT 1 ";
$result=mysqli_query($connection,$query);
if(!$result){echo "no results";}
while($selected=mysqli_fetch_assoc($result)){
$link=$selected['name'];
echo $ran_name= "Click here";
?>
// this code works but i dont want to be able to use Click here i want to be able to
generate the results once the submit button is clicked , the submit button must open the new tab.I think javascript must be used but i dont know how.
May be, something like this?
<?php
..
echo $ran_name= "<script> document.location.href='".$link."';</script>";
..
?>
More about location object http://www.w3schools.com/jsref/obj_location.asp.
Way 1
< input type="button" value="Open Window"
onclick="window.open('< ?php echo $link;?>')">
OR:
onclick="window.location.href='< ?php echo $link;?>','_blank'";
Way 2:
< form action="< ?php echo $link;?>" method="post" target="_blank">
...
< /form>
p/s: I don't know how to show code with format. (same you);
maybe you try this one? that's should do what you want
<?php
$query="SELECT * FROM names_table ORDER BY RAND() LIMIT 1 ";
$result=mysqli_query($connection,$query);
if(!$result) {
exit("no results");
}
while($selected=mysqli_fetch_assoc($result)){
$link=$selected['name'];
}
// Redirect to page
if (defined($link) && !empty($link))
header("Location: /$link");
?>