How to get and store menu values in php - php

First sorry for my bad english. below is my form image i have a form in my My Website first how to get the values from menu to text box then store the values in to database using Php .i have attached my code and image.I am beginner in Php .
Please help me
HTML CODE
<div class="taxi-form-full">
<div class="container">
<form method="POST" action="">
<div class="menu-types">
Standart
Business
Vip
Bus-Minivan
</div>
<div class="row forms">
<div class="col-md-3">
<div class="form-group">
<input type="text" id="searchTextSrc" name="source" value="" placeholder="From Address..." class="ajaxField"><span class="fa fa-map-marker"></span>
<input type="hidden" id="citySrc" name="citySrc" />
<input type="hidden" id="cityLatSrc" name="cityLatSrc" />
<input type="hidden" id="cityLngSrc" name="cityLngSrc" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<input type="text" id="searchTextDes" name="destination" value="" placeholder="To..." class="ajaxField"><span class="fa fa-map-marker"></span>
<input type="hidden" id="cityDes" name="cityDes" />
<input type="hidden" id="cityLatDes" name="cityLatDes" />
<input type="hidden" id="cityLngDes" name="cityLngDes" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<input type="text" id="phone" name="phone" value="" placeholder="Phone Number" class="ajaxField required"><span class="fa fa-phone"></span>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<input type="text" id="text" name="datetime" value="" placeholder="Date and Time" class="ajaxField js-datetimepicker"><span class="fa fa-calendar"></span>
</div>
</div>
</div>
<input type="submit" name="submit" value="submit" class="btn btn-lg btn-red aligncenter">
</form>
</div>
</div>
Php Code
<?php
$hname = 'localhost';
$uname = 'root';
$pword ='';
$dbase ='sample';
$con = mysqli_connect($hname, $uname , $pword ,$dbase );
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['submit'])){
$phone = $_POST['phone'];
$datetime = $_POST['datetime'];
$query = mysqli_query($con,"insert into test(phone, datetime) values ('$phone', '$datetime')");
}

Instead of using anchors as part of your navigation you can use radio fields.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio
This will then send you the appropriate menu item chosen via the $_POST variable.
<label class="type-1">
<input type="radio" name="menu" value="Standart" checked /> Standart
</label>
<label class="type-2">
<input type="radio" name="menu" value="Business" /> Business
</label>
<label class="type-3 red">
<input type="radio" name="menu" value="VIP" /> Vip
</label>
<label class="type-4">
<input type="radio" name="menu" value="Bus" /> Bus-Minivan
</label>
In PHP you'll receive the value based on what option was checked.
<?php
$menu = $_POST['menu'];
You'll need to change the styling of the radio fields to match what you had for your anchors. As the input is within the label you can style the label and hide the input field to keep the same look and feel.
Styling radio button
This method is far more attractive than capturing the clicks with JavaScript and injecting the value into a text field as it'll work with or without JavaScript.

One of the ways you could achieve this is by using AJAX. In my example, I'll use jQuery AJAX, which will require you to include a jQuery library to your application. The reason I personally use jQuery is because it simplifies the JavaScript code a lot, and so it makes it easier to write and understand.
Now, in your question, you mention the element textbox, but I do not see that element anywhere? Do you mean your input fields, which is an entirely different thing? Since I don't see any textbox elements, I am going to assume that you mean input fields.
Before jumping straight into the AJAX function, I'd like to explain a few things. Basically what we will do with the AJAX function is to parse values to another page, which will handle our database logic, such as INSERT the data etc.
The key elements in an AJAX function is its options that you define in the function.
type, which is the data type of your data that you are going to
parse. Examples would be GET and POST
url, which is where you define the page where the data that will get parsed.
data, which is where you will define your data variables that you will be parsing.
optionally, success, which is a function where you can define certain actions to occur upon success of your AJAX function.
The AJAX function:
function submitForm() {
$.ajax({
type : "POST",
url : "/your_page.php",
data : {
standart: $("[data-value='Standart']").val(),
business: $("[data-value='Business']").val(),
vip: $("[data-value='VIP']").val(),
bus: $("[data-value='Bus']").val(),
searchTextSrc: $("#searchTextSrc").val(),
citySrc: $("#citySrc").val(),
cityLatSrc: $("#cityLatSrc").val(),
searchTextDes: $("#searchTextDes").val(),
cityDes: $("#cityDes").val(),
cityLatDes: $("#cityLatDes").val(),
cityLngDes: $("#cityLngDes").val(),
phone: $("[name='phone']").val(),
datetime: $("[name='datetime']").val()
},
success: function (html) {
//do something on success
}
})
}
Note that I encapsulated the AJAX function into another function that I named submitForm(). You can choose to call this function onclick on your button in order to trigger your AJAX function.
<button onclick="submitForm();">Submit content</button>
Since you weren't entirely specific on precisely which elements values you'd like to retrieve, I targeted them all. I am actually uncertain if $("[data-value='whatever']") is a valid selector. If it's not, simply give them an id or a name attribute to go by instead.
Now, since I defined the type in the AJAX function to be POST, you will have to use $_POST in your PHP file to fetch the data that has been parsed from the AJAX function.
In your PHP page:
<?php
$standart = $_POST['standart'];
$business = $_POST['business'];
$vip = $_POST['vip'];
$bus = $_POST['bus'];
$searchTextSrc = $_POST['searchTextSrc'];
$citySrc = $_POST['citySrc'];
$cityLatSrc = $_POST['cityLatSrc'];
$searchTextDes = $_POST['searchTextDes'];
$cityDes = $_POST['cityDes'];
$cityLatDes = $_POST['cityLatDes '];
$cityLngDes = $_POST['cityLngDes '];
$phone = $_POST['phone '];
$datetime = $_POST['datetime '];
/* You now have all your parsed variables as PHP variables
that you can choose to INSERT into your database. */
$hname = 'localhost';
$uname = 'root';
$pword ='';
$dbase ='sample';
$con = mysqli_connect($hname, $uname , $pword ,$dbase );
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$sql="INSERT INTO test SET phone='$phone', datetime='$datetime'";
mysqli_query($con, $sql);
?>
However, please note that you are wide open to SQL Injections, which is one of the reasons #R. Chappell dropped this link in the comment section.

Related

Reopen toggle after form submit

I am still working on my school project, which is almost finished.
With your help, I successfully created a working system that allows users to write, edit and delete data to/from the database.
The only problem I have right now us "user-friendly form." I managed to create auto-focus, insert correct values on edit so the user can see what was previously written in that field, etc.
I have my forms hidden with jquery. When a user clicks add, the form slides in. What I need to achieve is: "when a user clicks submit and the page refreshes and adds the element to the database, the form should appear again so users can add data faster."
Here is my code.
$(document).ready(function() {
$('#x').click(function() {
$('.y').toggle("slide");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="x">Click</div>
<div class="y" style="display: none;">
<div class="container">
<form action="insertzunanja.php" method="POST" id="x">
<input type="hidden" name="narocilo" value="0.1412312">
<input type="hidden" name="id" value="id-1">
<input type="text" name="dolzina" style="width:49%;" placeholder="Dolzina (v cm)">
<input type="text" name="sirina" style="width:49%;" placeholder="Sirina (v cm)">
<input type="text" name="kolicina" value="1" style="width:49%;" placeholder="Kolicina">
<input type="text" name="opombe" style="width:49%;" placeholder="Opombe">
<input type="submit" value="Send">
</form>
</div>
</div>
Thanks and best regards.
You can use AJAX call to send the data to php file instead of form action. According to your code you will have something like this:
<div id="x">Dodaj</div>
<div class="y" style="display: none;">
<div class="container">
<input type="hidden" name="narocilo" value="<?php echo $randomNum; ?>">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="dolzina" style="width:49%;" placeholder="Dolzina (v cm)">
<input type="text" name="sirina" style="width:49%;" placeholder="sirina (v cm)">
<input type="text" name="kolicina" value="1" style="width:49%;" placeholder="Kolicina">
<input type="text" name="opombe" style="width:49%;" placeholder="Opombe">
<input id="sub" type="submit" value="Send">
</div>
</div>
$(document).ready(function(){
$('#x').click(function() {
$('.y').toggle("slide");
});
});
$("sub").click(function(){
$.post("insertzunanja.php",
{
dolzina: $("input[name=dolzina]"),
sirin: $("input[name=sirina]")
},
function(){
$("input[name=dolzina]").val("");
$("input[name=sirina]").val("");
if($('.y').is( ":hidden" )) {
$('.y').toggle("slide");
}
});
});
Basically, when you click on button you call php with AJAX POST request passing two values dolzina and sirin retrieved by the html code(note: you have more values to pass so change it accordingly) to php file. Jquery deletes the values of the input fields and check if input fields are shown. If not the inputs fields are shown.
If you are using PHP to process the form submission and generate the code in your question, and you always want the form to be displayed after submission, you can do this:
At the PHP code identify submission (e.g. isset($_REQUEST['id']) ).
[if #1 is true] On generating jQuery code, add $('.y').show(); within the ready function (but separated from the existing click function).
Example:
<?php
// your existing code...
?>
$(document).ready(function() {
<?= ( isset($_REQUEST['id']) ? '$(".y").show();' : '' ); ?>
$('#x').click(function() {
$('.y').toggle("slide");
});
});
<?php
// your existing code...
?>

Radio button only returns "on" when submitted

I am very new to PHP and I am trying to display the value of a selected radio button in a string. But all I get returned is "on" instead of the value associated with the selection. Any help would be great!
<form action="Handle_form_PHP.php" method="post">
<div class= "row">
<div class ="col-25">
<label for="student">Student</label>
</div>
<div class ="col-75">
<input type="radio" name="student" value ="student">
</div>
</div>
<div class= "row">
<div class ="col-25">
<label for="student">Employee</label>
</div>
<div class ="col-75">
<input type="radio" name="student" value = "employee">
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
This is the PHP I am using to print:
// Create a shorthand for the form data:
$fname = $_REQUEST['firstname'];
$lname = $_REQUEST['lastname'];
$address = $_REQUEST['address'];
$state1 = $_REQUEST['state1'];
$state2 = $_REQUEST['state2'];
$student = $_POST['student'];
// Print the submitted information:
echo "<p>Thank you, <b> $student </b>, <b>$fname $lname</b>, for the filling out our survey:<br>
<p>We will Send you your report at: <i>$address</i>, <i>$state1</i><i>$state2</i>.</p>\n";
If your $_POST['student'] superglobal variable was holding a value of 'on', then the issue has nothing to do with method case-sensitivity.
The default value for a radio button is 'on' unless you provide a value attribute inside the radio button tag.
Let me prove it to you. Go to [cringe] https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_form_checkbox then paste the following snippet in the left-side box, then Run, then Submit.
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php" method="get">
<input type="radio" name="student" checked> Student<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
This is submitting with a method of get (notice the lowercase get is inconsequential. post will behave the same way). See that without a value in the student radio input, the submitted value is on.
If you write value="Red42" inside the radio input, you will no longer receive on; the submitted value is Red42.
use POST not post when saying method:
<form action="Handle_form_PHP.php" method="POST">
not
<form action="Handle_form_PHP.php" method="post">
For the record, the book was incorrect and had "post"

I am stuck while writing MySQL query to submit the content of a form which has text & checkbox

I have a form that had text and dropdowns. Now the client wants to use checkbox instead of dropdown. How to I change the query . Here is my code:
Form is in join.php
<form name="pantryinfo" id="pantryForm" method = "post" action="email.php" data-toggle="validator" role="form">
<label>Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Pantry Name" required>
<label>Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Enter Street address" >
<p class="help-block"></p>
<input type="checkbox" id="snapeligible" name="snapeligible" value="Yes">SNAP Eligilble<br>
<label>Community Meal?
select class="form-control" id="communitymeal" name="communitymeal" required >
<option></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</label>
<input name="submit" type="submit" id="submit" value="Add Food Provider" class="btn btn-primary center-block">
</form>
The field SNAP Eligilble was a dropdown just like Community Meal but now is a check box.
My earlier query was as follows in email.php
require 'config/connectDB.php';
//set variables from the form
$pname = $_POST['name'];
$paddress = $_POST['address'];
$psnapeligible = $_POST['snapeligible'];
$pcommunitymeal = $_POST['communitymeal'];
$sql = "INSERT INTO temp(pan_id, pname, paddress, psanpeligible, pcommunitymeal, )
VALUES(NULL,'$pname', '$paddress', '$psnapeligible', '$pcommunitymeal',)";
I am not sure how to append the query to include data from the check box only when the checkbox is selected as its not a required field.
An unchecked checkbox will not even be found in the $_POST array. This means to see from the PHP side whether the box was checked, all you have to do is look at whether the matching variable is set.
Change:
$psnapeligible = $_POST['snapeligible'];
To:
$psnapeligible = isset($_POST['snapeligible']) ? 'yes' : 'ho';
Make an IF-Statement, where you proof if the Value of the Checkbox is set.
Is it set use this Statement
Else use the another Statement without the psnapeligible
if (isset ($psnapeligible)) {
$sql = "...";
else {
$sql = "...";
}
you can chek in your php page (email.php) if your chek box is set or not ...
if (isset($_POST['snapeligible'])) {
$psnapeligible = $_POST['snapeligible'];
}
else {
$psnapeligible = "No" ;
}

Form Action Process.php file not echoing results from mySQL DB

Currently, I have an index.php file with a form and a text input from the user as well as a submit button. When the submit button is pressed, the process.php file is supposed to get the data and echo it out. However, it just sends me to a blank page and does not echo anything out. I am well aware that I would need to style it the page, etc... But it just isn't echoing out at all. I am already connected to the mySQL DB with another php script and have tested that and it works fine so I know I am connected. What am i doing wrong?
index.php
<form action="process.php" form method="post" id="myForm">
<div class="col-xs-12 col-md-6">
<div class="input-group">
<span class="input-group-addon">
<input aria-label="..." type="checkbox" id="checkbox1">
</span>
<input aria-label="..." class="form-control" type="text" id="food1">
</div>
</div>
<input type="submit" value="Submit">
</form>
process.php
<?php
//Check whether the form has been submitted
if($_POST['submit'] == "Submit")
{
$varFood1 = $_POST['food1'];
$sql = "SELECT menu.dish FROM menu WHERE menu.description LIKE '%varFood1%'"; // sql query
$result = mysql_query($sql);
// Loop the recordset $result
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($result)) {
echo "Items : {$row['dish']}\n";
}
}
?>
Use name attribute not id. <input aria-label="..." class="form-control" type="text" id="food1"> Try printting out the POST in the future.
<input aria-label="..." class="form-control" type="text" id="food1" name="food1">
Additional changes...
$varFood1 = mysql_real_escape_string($_POST['food1']);
$sql = "SELECT menu.dish FROM menu WHERE menu.description LIKE '%$varFood1%'";
without escaping you open yourself to injections. You should consider switching driver to mysqli or PDO as well.
The problem is that you are checking for $_POST['submit'], which the process.php file does not see, because it does not exist in the POST array. Solution: give your submit button a name, instead of this:
<input type="submit" value="Submit">,
which is what you have, do this:
<input type="submit" name="submit" value="Submit">

Form / ajax / PHP issue

I am trying to make a small form that lets the user pick one element from 3 different radiobutton lists to set one element as the users active element (that will be stored to MySQL). Somehow along the way it does not work and I can not seem to figure out why, perhaps someone of you can see what I did wrong?
HTML:
<form name="activeForm1" method="post">
<fieldset data-role="controlgroup">
<div class="ui-radio">
<input type="radio" name="active" value="1" id="1">
<label for="1"></label></input>
</div>
<div class="ui-radio">
<input type="radio" name="active" value="2" id="2">
<label for="2"></label></input>
</div>
<div class="ui-radio">
<input type="radio" name="active" value="3" id="3">
<label for="3"></label></input>
</div>
</fieldset>
<div data-role="footer">
<input type="submit" href="#" onclick="setActive(1)"/>
</div>
</form>
JavaScript / Ajax call
function setActive(formid)
{
$.ajax(
{
type:'POST',
url:'active.php',
data:$('#activeForm'+formid).serialize(),
success:function(response)
{
}
}
);
}
PHP code:
session_start();
include('connectToDb.php');
$id = $_SESSION['id'];
if (isset($_POST['active']))
{
$formValue = $_POST['active'];
mail('my#mail.com','Test',$formValue,'From: dummy#mail.com');
mysql_query(/* UPDATE MySQL */);
header("Location: main.php");
}
else
{
mail('my#mail.com','Test','No data recieved!','From: dummy#mail.com');
}
So it works up until the if (isset($_POST['active'])) but then mails me that no data was recieved. I already have 2 similar forms on the same page and they are way bigger and has no problems running. Can't figure out what I did wrong here.
Wrong code :
data:$('#activeForm'+formid).serialize(),
#activeForm is not an id, it is the name of the form tag,
Correct the form tag to,
<form name="activeForm1" id="activeForm1" method="post">
Replace following line
data:$('#activeForm'+formid).serialize(),
with
data: $('form[name="activeForm'+formid+'"]').serialize(),
change
<input type="submit" href="#" onclick="setActive(1)"/>
to
<input type="button" href="#" onclick="setActive(1)"/>
and then it should work

Categories