Handle HTML <input> Attribute [duplicate] - javascript

This question already has answers here:
How to get input field value using PHP
(7 answers)
Closed 6 years ago.
I am writing basic user register page,
My register page contain : usermail ,password, plan type.
There are three plans for plan type.
Three plans are: basic, sliver and gold.
The register_main.php is to store user information in Mysql.
I met issue that is when I click basic or sliver or gold plan, the page will go to register_main page .
I want sent user information only to server ,when they click sign in.
Can anyone help me to solve this issue?
HTML Code:
<html>
<head>
<title>Register</title>
<meta charset="UTF-8">
<!-- Include JS File Here -->
<script src="Script/register_validate.js">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
</script>
</head>
<body>
<form name="registerform" action="register_main.php" method="post" onsubmit="return validate()">
<p id="benefits_text" class="white size_8">Benefits:</p>
<input id="type_basic" type ="image" name="basicPlan" " src="basic.png">
<input id="type_silver" type ="image" name="silverPlan" " src="silver.png">
<input id="type_gold" type ="image" name="goldPlan" " src="gold.png">
<div id="userinfo_content">
<p id="email_text" class="white size_8">Email Address</p>
<input id="email_input" name="userEmail" type="text"class="sign_input">
<p id="password_text" class="white size_8">Password</p>
<input id="password_input" name="password" type="password">
<p id="confirmPW_text" class="white size_8">Confirm Password</p>
<input id="confirmPW_input" name="confirm_password" type="password">
<input id="btn_signin" type ="image" alt ="submit" src="signin.png">
</div>
</form></body>
</html>
register_main.php
include ("config.php");
require ("encrypt.php");
session_start ();
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
// Get userEmail from client side and create a legal SQL string that you can use in an SQL statement.
$user_emailaddress = mysqli_real_escape_string ( $db, $_POST ['userEmail'] );
// Get password from client side and create a legal SQL string that you can use in an SQL statement.
$user_password = mysqli_real_escape_string ( $db, $_POST ['password'] );
// Get planType from client side and create a legal SQL string that you can use in an SQL statement.
$user_planType = mysqli_real_escape_string ( $db, $_POST ['planType'] );
// Create user.
// Note user Id is generated when a new record is inserted into a table.
$sql = "INSERT INTO admin (emailAddress,passcode,planType) VALUES ('$user_emailaddress','$user_Newpassword','$user_planType')";
$result = mysqli_query ( $db, $sql );
// if create user a successfully, jump to welcome page.
// otherwise print error information
if ($result ) {
echo "New record created successfully";
$_SESSION ['login_user'] = $user_emailaddress;
header ( "location: welcome.php" );
} else {
echo "Error: " . $sql . "<br>" . mysqli_error ( $db );
}
// Close Database
mysqli_close ( $db );
}
?>

the problem with your form is that the input tag with type="image" acts as a submit button when clicked. Check out this link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/image.
I guess that in your use case, you want these images to act as selection buttons for the available plan types. So I think you could replace then for an image tag with a radio button, or a select input with the three plans.

Related

Getting response from sending form in textbox

I'm trying to make a website that automatically uses this script to get amount of bitcoin in an wallet :
<?php
$address = $_GET["address"];
$satbalance = file_get_contents('https://blockchain.info/q/addressbalance/'.$address.'');
$btcbal = ($satbalance) / 100000000;
echo $btcbal;
?>
and I'm trying to make page that has my clients username and password in textarea box and when I enter the bitcoin wallet address from my user to check the balance from multiple input boxes and show the value in the box in front of address box.
Image of the page that needs this job done
How can I get the response from the form and display in another box or variable.
Thanks.
Wrap the fields in a form tag and submit to the same page.
Using your code example, this example show a simple form and handling the POST with PHP. This hasn't been tested but is an example of how to handle a post using the $_POST super global.
<?php
$btcbal = null;
// Check if there is POST data
if (!empty($_POST)) {
$address = $_POST['address'];
$satbalance = file_get_contents('https://blockchain.info/q/addressbalance/'.$address.'');
$btcbal = ($satbalance) / 100000000;
}
?>
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="text" name="btc_address">
<button type="submit">Submit</button>
</form>
<p>Balance: <?php echo $btcbal ? $btcbal : 'N/A'; ?></p>

PHP form handling- display error message using javascript

I have a form.php file that redirects to a sendformdata.php file when I submit the form. However, I can't get the sendformdata.php file to display an error message within the form when the proper fields aren't filled out.
I am simply redirected to the include file, db_connect.php, which shows up as a blank page. How can I get the page to stay on form.php and display an error message in html? This is my current sendformdata.php file:
<?php
include_once('db_connect.php');
$lokotitle = $description = $category = $showyourname = $yourname = $lat = $lng = "";
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$lokotitle=$_POST['lokotitle'];
$description=$_POST['description'];
$category=$_POST['category'];
$showyourname=$_POST['showyourname'];
$yourname=$_POST['yourname'];
$lat=$_POST['lat'];
$lng=$_POST['lng'];
// Validation will be added here
if(empty($lokotitle)) {
$error_message = "Please input a Loko title.";
?><script>$('#notitle'.text($error_message));</script><?php
exit;
}
if(!isset($error_message)){
//Inserting record in table using INSERT query
$insqDbtb="INSERT INTO `new`.`web_form`
(`lokotitle`, `description`, `category`, `showyourname`, `yourname`, `lat`, `lng`) VALUES ('$lokotitle', '$description', '$category', '$showyourname', '$yourname', '$lat', '$lng')";
mysqli_query($link,$insqDbtb) or die(mysqli_error($link));
?><script>window.location.href = "../index.php"; </script> <?php
exit;
}
}
?>
This is a section of form.php that I am trying to display an error message in:
<form class="form-horizontal" role="form" action="handleform/sendformdata.php" method="POST">
<legend></legend>
<div class="form-group">
<label for="lokotitle" class="col-sm-2">Loko Title</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="lokotitle" id="lokotitle" placeholder="Title">
<span id="notitle"></span>
</div>
Thanks in advance for the help!
I recommend you to use both html5 required attribute which will force the user to enter the data. But remember the user can bypass front end validation (by means of inspect element), hence back end validation is also necessary.
Use required attribute like:
<input type="text" required />
You can try this
if(empty($lokotitle)) {
$error_message = "Please input a Loko title.";
echo "<script>
document.getElementById('#notitle').value='".$error_message."';".
"</script>";
exit;
}
Let me know if this solves your problem

How to reload user defined tag in CMS Made Simple

I have a html file which loads a list from my database and allows the front end user to remove a particular entry.
The HTML Code looks like this:
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend=$("#clientid").val();
$("#responseDiv").html("<h2>Removing from Database...</h2>");
$.post("RemoveClient.php",{
ClientId: dataSend
},function(data) {
$("#responseDiv").html(data);
$("#clientlist").empty();
$("#clientlist").html("{client_list nocache}");
});
return false;
}
// ]]></script>
</p>
<div id="MainForm"><form class="form" onsubmit="return sendForm()">
<h2 class="formstyle">Client Wizard</h2>
<p>Please fill all the required fields.</p>
<div id="clientlist">{client_list nocache}</div>
<p><input style="font-size: 1.5em; font-color: #000000;" onclick="sendForm()" type="submit" value="Delete" /></p>
</form>
<div id="responseDiv"> </div>
</div>
The UDT called for {client_list} is given below.
$dbhost='127.0.0.1';
$dbuser='user';
$dbpass='pass';
$dbname='dbname';
$conn=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
die('Could not connect:'.mysqli_connect_error());
}
$sql="SELECT clientid,clientname FROM client order by clientid";
echo "<label> Select Client: </label>";
echo "<select id=clientid name=clientid>";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
echo "<option value=".$row['clientid'].">".$row['clientname']."</option>";
}
echo "</select>";
Now, once I click on delete, I want the drop down list to refresh with the new list not having the deleted client. I tried doing that by emptying the div and then reloading the UDT. Unfortunately this does not seem to be working, the way I want it to, as the list does not get refreshed until and unless I refresh the page. Is there anyway I can make this work?
The quick/easiest option would be to assign it an id and to remove the entry via javascript.
Second, would be to have RemoveClient.php return it as part of the response from the AJAX.
var response = data.split('|');
$("#responseDiv").html(response[0]);
$("#clientlist").html(response[1]);
Third, I would strongly advise against this way but it is the question you ask, put the UDT alone on new page then load the page with the ?showtemplate=false parameter.
$("#clientlist").load("//www.mydomain.com/myudt.html?showtemplate=false");

How can I permanently disable a button after completing a form? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm currently in the process of creating a reservation page for our company. What I would like to do is have it to where when the user clicks the Reserve Now Button a form pops up for them to complete. After the user completes the form the reserve button is disabled permanently to everyone accessing the site. How can I accomplish this? I am not very well versed in java script or php. Any help would be greatly appreciated.
<div class="container">
<div class="row">
<div class="col-lg-12">
<table class="table table-striped">
<tr>
<td>Product</td>
<td>RESERVE NOW</td>
</tr>
</table>
<form>
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
</div>
</div>
</div>
I have mocked up an example that can be found here:
https://jsfiddle.net/rman215/gw2m53w9/1/
If I understood you you want to provide ability ti reserve something, but only for 1 person, right?
So, you can store flag in database (for example in disabled_at [timestamp, default = null] column). When somebody click on button and call processing page (via ajax or simple redirect) set flag disabled_at value NOW(). And each time on processing page is disabled_at IS NULL. If yes - save first and last name to database.
On page with form need to add attribute disabled to submit button if disabled_at IS NOT NULL
EDIT:
disable.php
<?php
function reserveItem($name = null, $value = null)
{
$name .= '.reserved';
$value = $value ? $value : 1;
return file_put_contents($name, $value);
}
function isDisabled($name = null)
{
return file_exists($name . '.reserved');
}
$disabled = isDisabled('item1');
if (isset($_POST['submit'])) {
$name = isset($_POST['firstname']) ? $_POST['firstname'] : '';
$lastName = isset($_POST['lastname']) ? $_POST['lastname'] : '';
if (!$disabled) {
reserveItem('item1', $name . $lastName);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<table class="table table-striped">
<tr>
<td>Product</td>
<td>RESERVE NOW</td>
</tr>
</table>
<form method="post" action="disable.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit" <?= $disabled ? 'disabled' : ''; ?>>
</form>
</div>
</div>
</div>
</body>
</html>
Note: code written in editor only and not tested.
give id to submit button and on click of submit call this function
function disableButton() {
$("#idOfButton").attr("disabled","disabled")
}
After form submit you will get the success response. After getting success just disable the Reserve Now Button using this code :
If you are using ajax to submit form then you need to do that :
suppose Reserve Now Button id : reserve_btn_id
$.ajax({
// your code....
}).done(function() {
$("#reserve_btn_id").attr("disabled","disabled");
});
Since JavaScript is executed every time a client loads the page, you cannot insert JavaScript code to block the button.
I suggest you to use a simple MySQL database, something like:
CREATE TABLE Items(
ItemID INTEGER AUTO_INCREMENT PRIMARY KEY,
Description VARCHAR(255),
IsReserved TINYINT(1) //this works like a boolean
);
So that your page will have a select of all items, something like this:
SELECT * FROM Items ORDER BY ItemID
And then you will print them with something like this:
$server = "localhost";
$username = "root";
$password = "root";
$database = "mydatabase";
$connection = mysqli_connect($server, $username, $password, $database);
$result = mysqli_query($connection, "SELECT * FROM Items ORDER BY ItemID");
if (mysqli_num_rows($result) > 0){
echo("<form action=\"mypage.php\" method=\"post\">");
while($row = $result->fetch_assoc()){
echo("input name=\"id\" type=\"hidden\" value=" . $row['ItemID'] . ">"); //this input type hidden isn't shown on the page but we use it to store the id of the item so that we can retrieve it on the PHP page on submit
echo("ID: " . $row['ItemID']);
echo("Description: " . $row['Description']);
if ($row['IsReserved'] == 1){
echo("<button class=\"mybutton\" type=\"submit\" disabled>Reserve</button>");
}
else{
echo("<button class=\"mybutton\" type=\"submit\">Reserve</button>");
}
}
echo("</form>");
}
else{
echo("No data");
}
Then to update the status of an item that is reserved, just update the status when the form has been submitted to the other PHP page, you will have something like this:
$server = "localhost";
$username = "root";
$password = "root";
$database = "mydatabase";
$connection = mysqli_connect($server, $username, $password, $database);
$id = (int) $_POST['id']; // here you get the id of the hidden input
// $data = mysqli_query($connection, "SELECT * FROM Items WHERE ItemID = $id");
/* $data now contains all info stored about the item, you can use it if you
need to insert those info in another table, etc. */
// UPDATING STATUS
mysqli_query($connection, "UPDATE Items SET IsReserved = 1 WHERE ItemID = $id");
mysqli_close($connection);
So this is it, basically, I hope it helps you with your project :)
I leave you this guide on how to handle Forms & their data with PHP.

Merging 2 search forms into 1 input, plus checkboxes

On my site I have a main search (powered by Google, placed throughout the site) and I have now created a second search (on its own page, which searches my DB for images based on user input text) which is a totally separate search to the google one.
What I want to do -
I want both Search forms to share a single text input field, but allow the user to choose which search to use (Google or Images Only) via radiobutton.
So we'd have:
[search input field][go] (o)Use Google (o)Image Search only
I'm no coder but can hack enough to just about get by, it just takes me a day or two to figure out and get working.
What I need and would save me a great deal of time, as I'm stumped on how to proceed with this or if it is even possible! If someone could tell me A) If it's possible, and B) A few pointers if it is. For instance I'm guessing it will probably need a bit of JavaScript to make it possible?
Any pointers would be appreciated, then I can see what I can do.
All the best,
Chris
// My Stand-alone Image Search Page ////////////////////////////////
<form method="post" action="imagesearch?go" id="search-form">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
// code for above form //
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
$sql="SELECT ID FROM ImageTable WHERE Name LIKE '%" . $name . "%' Order by Date Desc LIMIT 50";
//-run the query against the mysql query function
$result=mysql_query($sql);
// Create while loop and loop through result set//
$content .= ' <p><div id="wrapper">';
while($row=mysql_fetch_array($result)){
$id=$row['ID'];
$img = new Image($id);
// Format results//
$content .= '<div id="imgrt"><img src="/img/M/'.$img->ID.'.jpg" class="searchimg"><br>'.$img->Name.'';
$content .= '</div>';
}
$content .= '';$content .= '</div>';
}
else{
$content .= ' <p>Please enter a search query</p>';
}
}
}
// End of Stand-alone image search page /////////////////////////
---------------------------------------------------------------------------
// My sites main Google powered Search
<form action="http://www.example.com/gsresults" id="cse-search-box" class="searchmain">
<input type="hidden" name="cx" value="partner-pub-XXXXXXXXXXXXXXX" />
<input type="hidden" name="cof" value="FORID:XX" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" class="mainsearch">
<input type="submit" name="sa" value="Go" class="mainsearchbutton"/>
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang="></script>
OK so here we go. If you plonk this in an empty html file you can see it in action (Tried to make a jsfiddle but didnt work for some reason). What this does is set an "active" id on the selected combo option, and when you click the submit button it grabs the value of the combo option with that id, and goes to the page of that value. so if you click google and then the button you go to google.html, and same goes for image, image.html. If you want some more specifics you can ask, but thats the main logic there.
<script>
function replaceActive(obj) {
var activeElm = document.getElementById("active");
activeElm.id = activeElm.id.replace("active", "");
obj.id = "active";
}
function formFunction(obj) {
obj.action = document.getElementById("active").value + ".html";
}
</script>
<form action="#" onsubmit="return formFunction(this);" method="post">
<input type="text" />
<select>
<option value="google" id="active" onclick="replaceActive(this);">Google</option>
<option value="image" onclick="replaceActive(this);">Images</option>
</select>
<input type="submit" />
</form>
Basically you can change that "formFunction()" function's code and and use "document.getElementById("active").value" to do what ever you wanted to do.

Categories

Resources