How to check if content of an html element is empty? - javascript

I was building a simple PHP login form that contains both required fields and validation. regardless required fields, I want to display an error message for each input element that had not been filled. But I come across a problem on the way. The span element I use for styling does not disappear when there is no content in the span element. I wrote some javascript code and it did not work. I want the span element to hide when there is no content because the $nameerr equals to "" at the start. When the $nameerr equals to "Name Required" string, the span element should be visible only at the time. How to achieve that?
Note: I only want to test for $name and $nameerr first before implementing other variables, So other variable is "".
Here is my code for php:
<?php include('validate.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Learning PHP</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row justify-content-center" style="height:auto;background-color:#ffcb05;">
<div class="col-lg-4" style="background-color:#fcd670;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<div class="d-flex flex-column">
<div class="mb-3">
<label for="name" class="form-label">Name:</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Please enter your name" style="width:100%;">
<span class="badge bg-danger float-end" id="error1">
<?php echo $nameerr; ?>
</span>
</div>
<div class="mb-3">
<label for="email" class="form-label">E-mail</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Please enter your e-mail" style="width:100%;">
</div>
<div class="mb-3">
<label for="website" class="form-label">Website</label>
<input type="url" name="website" id="website" class="form-control" placeholder="Please enter your website" style="width:100%;">
</div>
<div class="mb-3">
<label for="comment">Comment</label>
<textarea name="comment" id="comment" cols="45" rows="5" class="form-control"></textarea>
</div>
<div class="mb-3">
<label>Gender</label>
<label for="male">Male</label>
<input type="radio" name="gender" id="male" value="male">
<label for="female">Female</label>
<input type="radio" name="gender" id="female" value="female">
<label for="other">Other</label>
<input type="radio" name="gender" id="other" value="other">
</div>
<div class="mb-3">
<button class="btn btn-primary float-end" type="submit">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script>
var content=document.getElementById('error1').innerHTML;
if(content==""){
document.getElementById('error1').style.display="none";
}else{
ocument.getElementById('error1').style.display="block";
}
</script>
</body>
</html>
Here is my validate.php file:
<?php
$name=$email=$website=$comment=$gender='';
$nameerr=$emailerr=$websiteerr=$commenterr=$gendererr='';
if($_SERVER["REQUEST_METHOD"]=="POST"){
if(empty($_POST['name'])){
$nameerr="Name Required";
}else{
$name=validateInput($_POST["name"]);
$email=validateInput($_POST["email"]);
$website=validateInput($_POST["website"]);
$comment=validateInput($_POST["comment"]);
$gender=validateInput($_POST["gender"]);
echo $name."<br>".$email."<br>".$website."<br>".$comment."<br>".$gender."<br>";
}
}
function validateInput($data){
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}

In my opinion. I think you don't need to use javascript to show/hide error content.
You can try below block code:
<?php if(!empty($nameerr)): ?>
<span class="badge bg-danger float-end" id="error1">
<?php echo $nameerr; ?>
</span>
<?php endif; ?>

You have padding there.
so you can try removing the class badge
<span class="bg-danger float-end" id="error1">
<?php echo $nameerr; ?>
</span>
or remove the padding from that class
.badge {
display: inline-block;
/* padding: 0.35em 0.65em;*/

You may use a client side approach (javascript).
Detect on submit whether the name field is empty
If yes, make the error1 message visible, else make it not visible
Add more blocks for further validation, if you wish
If no further errors, return true (to submit)
So change
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
to
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return validateform();">
and change
<span class="badge bg-danger float-end" id="error1">
<?php echo $nameerr; ?>
</span>
to
<span class="badge bg-danger float-end" id="error1" style="display:none;">
Name Required !!!!
</span>
and add the following :
<script>
function myTrim(x) {
return x.replace(/^\s+|\s+$/gm,'');
}
function validateform() {
if(myTrim(document.getElementById('name').value)==""){
document.getElementById('error1').style.display="block";
return false;
}else{
document.getElementById('error1').style.display="none";
}
// if no errors at all
return true;
}
</script>

Related

Having problem submitting a form without reload using jquery ajax

When i submit form it doesnot update value in database mysql.Its a form written in php.
here is my php and html. I want that the form should not reload and it must submit the changes in database without reloading the page and show preloader for 1 sec on submitting form.
HTML,PHP AND ACTION of form: Here action is the current page where this form is avalilable
detail_customer.php
<?php
$server = "localhost";
$username = "root";
$pass = "";
$dbname = "stinkspolitics_pl";
$conn = mysqli_connect($server, $username, $pass, $dbname);
if (isset($_GET['detail_customer'])) {
$quest_id = $_GET['detail_customer'];
$get_quest = "SELECT * FROM questions WHERE quest_id = '$quest_id'";
$getting_quest = mysqli_query($conn, $get_quest);
while ($row = mysqli_fetch_assoc($getting_quest)) {
$quest_title = $row['quest_title'];
$category_id = $row['category_id'];
}
}
if (isset($_POST['submit'])) {
$quest_t = $_POST['quest_t'];
$update = "UPDATE questions SET quest_title = '$quest_t' WHERE quest_id = '$quest_id'";
$run_update = mysqli_query($conn, $update);
if ($run_update) {
echo 'hello';
}
}
?>
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php
" method="POST" class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<?php echo $category_id ?>" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<?php echo $quest_title ?>" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
JS Code
index.js
$("#form-submit").on("submit", function () {
// e.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: formData,
success: function (data) {
$(".alert-success").show();
$(".alert-success").fadeOut(4000);
console.log(data);
},
error: function (data) {
$(".alert-danger").show();
$(".alert-danger").fadeOut(4000);
console.log(data);
},
});
return false;
});
Ajax Success Response But not updating data in mySQL
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php" method="POST"
class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<br />
<b>Warning</b>: Undefined variable $category_id in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>62</b><br />
" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<br />
<b>Warning</b>: Undefined variable $quest_title in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>66</b><br />
" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
The condition if (isset($_POST['submit'])) { will never evaluate to true, since there is no input element in the form with name="submit" (the button with name='submit' does not send the attribute by default).
Either change the condition:
if (isset($_POST['quest_t'])) { ...
Or, include an input element with name='submit', for example:
<input name="submit" type="hidden" />
Also, make sure to move the $_POST check at the beginning of the file and ensure that no other code will be evaluated in the PHP file (e.g. the rest of the HTML code) if a POST request has been received.
Just return false after at the end of the method.
jQuery has its own way of ensuring "preventDefault()" and it is just returning false from the submit handler.
Full background on this here:
event.preventDefault() vs. return false
Issue has been solved. By changing path and then putting path of js file again.

How to return second register form on submition?

I have a page with two registration forms individual and business type and individual type form is set as default the other form is hidden, it works fine. but when I switch it to second form and click on submit button it submits second form but returns to first form after submition even on errors it return to first form.
I want it to stay on second form on errors and after submition.
Here is my php :
if (isset($_POST["btnRegister"])) {
echo "Done";
}elseif (isset($_POST["btnbusiness"])) {
echo "Done";
}
HTML and js codes in my page:
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for(i = 0 ; i < radioName.length; i++){
document.getElementById(radioName[i].id.concat("Settings")).style.display="none";
}
document.getElementById(x.id.concat("Settings")).style.display="initial";
}
<div class="col-10 clmiddle">
<label for="production"><b>Individual</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development"><b> Business</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
</div>
First Form :
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second Form :
<div id="developmentSettings" style="display:none" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
EDIT: I changed JS to php, Here is the solution.
PHP codes (which get url):
$path = $_SERVER['REQUEST_URI'];
$Aurl = explode(",",$path);
for ($i=0; $i<count($Aurl);$i++){
$Burl = str_replace("?", "/", trim($Aurl[$i]));
}
$url = htmlspecialchars(basename($Burl));
$FormPostUrl = basename($path);
Html part :
Checkbox :
<div class="col-10 clmiddle" style="margin-top: 20px;">
<label for="production"><b>Individual</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php"); ?>" name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("register.php")){ echo 'checked="checked"';}?>>
<label for="development"><b>Business</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php?business");?>"
name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("business")){ echo 'checked="checked"';}?>>
</div>
First Form :
<?php if($url === htmlspecialchars("register.php")){?>
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second form:
<?php } elseif($url === htmlspecialchars("business")){ ?>
<div id="developmentSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
<?php } ?>
You can use PHP to control whether display:none is added to your divs or not. Use an if statement (or a ternary operator might be neater syntax in the context) to make the decision about what to echo. Since the default is to display the production settings form, we only need to check whether the other form has been submitted or not, in order to know whether to change that.
e.g. something like this (untested):
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" <?php echo (isset($_POST["btnRegister"]) ? "" : 'checked="checked"'); ?> />
and
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" <?php echo (isset($_POST["btnRegister"]) ? 'checked="checked"' : ""); ?> />
and
<div id="productionSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "style='display:none'" : ""); ?>>
and
<div id="developmentSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "" : "style='display:none'"); ?>>
P.S. Unless you've massively simplified these forms for the purpose of your example, they appear to be basically identical. It's questionable whether you actually need two separate forms at all. The only difference appears to be the choice between "individual" and "business" - that could be handled by a single form with a radio button to choose the type, which would then simplify how you handle the postback as well, and reduce the amount of duplicated code and HTML. Of course if you're actually capturing more distinct fields for these forms than you've shown, then these remarks don't really apply.

How to get dynamic buttons value when button is click in PHP?

I have created dynamic buttons in php. I need to get the value of that button when particular button is click. And when we click the button, all information is fetch in to the form.
Here is my code for buttonclick
<?php
function dash()
{
include 'config.php';
$sql = "SELECT roomno FROM roombook";
if($result = mysqli_query($db, $sql))
{
$str = '';
while($row = mysqli_fetch_array($result))
{
// generate array from comma delimited list
$rooms = explode(',', $row['roomno']);
//create the dynamic button and set the value
foreach ( $rooms as $k=>$v )
{
$str .= '<input type="button" onClick="showDiv()" name="btn_'.$k.'" value="'.$v.'" id="btn_'.$k.'"/>';
}
}
return $str;
}
else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
}
?>
<!Doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>room boking</title>
<link href="css/bootstrap1.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/front.css">
</head>
<body>
<form method="post" action="">
<div class =" row box col-md-4" >
<div style="color:black"><?php echo dash();?></div>
</div>
</form>
Here fetching the value in form code
<!DOCTYPE html>
<?php
include 'config.php';
if(isset($_POST['book']))
{
$roomno=$_POST['roomno'];
$roomtype=$_POST['roomtype'];
$location=$_POST['location'];
$charges=$_POST['charges'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$address=$_POST['address'];
$city=$_POST['city'];
$state=$_POST['state'];
$pincode=$_POST['pincode'];
$mobilenumber=$_POST['mobilenumber'];
$idtype=$_POST['idtype'];
$idnumber=$_POST['idnumber'];
$Adate=$_POST['Adate'];
$Ldate=$_POST['Ldate'];
//echo $roomno."<br>".$roomtype."<br>".$location."<br>".$charges."<br>".$firstname."<br>".$lastname."<br>";
if(strlen($firstname)<3)
{
echo "<script>alert('First name is to short')</script>";
}
else if(strlen($lastname)<3)
{
echo "<script>alert('Last name is to short')</script>";
}
else if(strlen($address)<3)
{
echo "<script>alert('UserName name is to short')</script>";
}
else
{
$query=" INSERT INTO customerbook(roomno,roomtype,location,charges,firstname,lastname,address,city,state,pincode,mobilenumber,idtype,idnumber,Adate,Ldate) VALUES('$roomno','$roomtype','$location','$charges','$firstname','$lastname','$address','$city','$state','$pincode','$mobilenumber','$idtype','$idnumber','$Adate','$Ldate')";
//$query="INSERT INTO customerbook(roomno,roomtype,location,charges,firstname,lastname,address,state,city,pincode,mobilenumber,idtype,idnumber,Adate,Ldate) VALUES('$roomno','$roomtype','$location','$charges','$firstname','$lastname','$address','$state,','$city','$pincode','$mobilenumber','$idtype','$idnumber','$Adate','$Ldate')";
if(mysqli_query($db, $query))
{
echo "<script>alert('booking seccessfully')</script>";
//header("Location:login.php");
}
else echo "error";
}
}
$sql = "SELECT roomno,roomtype,location,charges FROM roombook where roomno='101'";
if($result = mysqli_query($db, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$roomno=$row['roomno'];
$roomtype=$row['roomtype'];
$location=$row['location'];
$charges=$row['charges'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($db);
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>booking Form</title>
<!-- Bootstrap -->
<link href="css/bootstrap1.min.css" rel="stylesheet">
<link href="css/book.css" rel="stylesheet">
</style>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-1.12.4.js"></script>
<script src="js/book1.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="head" id="link">
<div class="panel panel-primary" style="margin:20px;">
<div class="panel-heading">
<center><h3 class="panel-title">booking Form</h3></center>
</div>
<div class="panel-body">
<form method="post" action="">
<div class="col-md-12">
<div class="form-group col-md-12 ">
<label for="roomno">Room Number* </label>
<input type="text" class="form-control input-sm" name="roomno" value='<?php echo $roomno; ?>' placeholder="">
</div>
<div class="form-group col-md-6">
<label for="type">Room Type*</label>
<input type="text" class="form-control input-sm" name="roomtype" value='<?php echo $roomtype; ?>' placeholder="">
</div>
<div class="form-group col-md-6">
<label for="location">Location*</label>
<input type="text" class="form-control input-sm" name="location" placeholder="">
</div>
<div class="form-group col-md-12">
<label for="charges">charges*</label>
<input type="text" class="form-control input-sm" name="charges" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="customer name">First Name*</label>
<input type="text" class="form-control input-sm" name="firstname" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="customer name">Last Name*</label>
<input type="text" class="form-control input-sm" name="lastname" placeholder="">
</div>
<div class="form-group col-md-12">
<label for="address">Address*</label>
<textarea class="form-control input-sm" name="address" rows="3"></textarea>
</div>
<div class="form-group col-md-4">
<label for="city">City*</label>
<input type="text" class="form-control input-sm" name="city" placeholder="">
</div>
<div class="form-group col-md-4">
<label for="state">State*</label>
<input type="text" class="form-control input-sm" name="state" placeholder="">
</div>
<div class="form-group col-md-4">
<label for="pincode">Pincode</label>
<input type="text" class="form-control input-sm" name="pincode" placeholder="">
</div>
<div class="form-group col-md-12">
<label for="mobile">Mobile Number*</label>
<input type="text" class="form-control input-sm" name="mobilenumber" placeholder="">
</div>
<div class = "form-group col-md-12">
<label for="years">Id Type *</label>
<select class="form-control input-sm" name="idtype">
<option>-- Select Id Card --</option>
<option>Pancard</option>
<option>Adhar Card</option>
<option>voting card</option>
</select>
</div>
<div class="form-group col-md-12">
<label for="idnumber">Id Number</label>
<input type="text" class="form-control input-sm" name="idnumber" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="arrival">Arrival Date</label>
<input type="text" class="form-control input-sm datepicker" name="Adate" placeholder="">
</div>
<div class="form-group col-md-6">
<label for="arrival">Leaving Date</label>
<input type="text" class="form-control input-sm datepicker" name="Ldate" placeholder="">
</div>
</div>
<div class="col-md-12">
<div class="form-group col-md-12 " >
<center><input type="submit" class="btn btn-primary" value="Submit" name="book"/><center>
</div>
</div>
</form>
</div>
</div>
</script>
</body>
</html>
You can create your button like this
$str .= '<input type="button" onClick="showDiv()" data-atribute-id="valueyouwant" name="btn_'.$k.'" value="'.$v.'" id="btn_'.$k.'"/>';
Script should be like
$("button").click(function() {
alert(this.id); OR
alert($(this).attr('id')); OR
alert($(this).attr('data')); OR
var btnid = $(this).attr('data');//which give you current clicked btn id
});
You can use this:
// is going to select all elements that its name start with *btn_* (your dynamic buttons)
$('[name^="btn_"]').click(function() {
//get the value of the button that was clicked
var buttonValue = $(this).val();
// send data to the other file using the action attribute of the form
$('form').submit();
});
Hope that can help.

How to validate a form in a bootstrap modal using PHP?

As soon as the form is submitted, the form is not validated and the modal is closed because the page is refreshed. I want the modal to stay open on submitting the form. The php is given below:
<?php
$nameerror = $studentiderror = $emailerror = "";
$subject = "Thank you for voting!";
$body = "Dear $_POST["name"], Thank you for voting for this sustainable initiative. Your vote is appreciated! Lots of love from the Beefarm Committee of the Erasmus Sustainability Hub!";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST["submit"]) {
if (empty(($_POST["name"])) {
$nameerror = "Please enter your name" }
if (empty($_POST["studentID"])) {
$studentiderror .= "Please enter your student ID";
} else {
$result = "Thank you for voting!";
mail($_POST["email"], $subject, $body);
}
};
}
Here is the HTML of the modal, the PHP is embedded in the HTML, where the error messages should be shown when the form is validated after submission:
<div class="container">
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">x</button>
<h4 class="modal-title">Vote!</h4>
</div>
<div class="modal-body">
<p>
Let us know what you think! <br/>
By voting, you as a student can have a say in the realisation of this project. Even if you vote
against having bees on campus, your vote is appreciated! <br/>
Thank you!
</p>
<form id="votingscreen" method="POST">
<?php echo $result ?>
<div class="form-group">
<label for="name">Name</label>
<?php echo $nameerror ?>
<input style="width: 180px" type="text" id="name" name="name" class="form-control" placeholder="Your name">
</div>
<div class="form-group">
<label for="studentID">Student ID</label>
<?php echo $studentiderror ?>
<input style="width: 180px" type="text" id="studentID" name="studentID" class="form-control" placeholder="123456AB">
</div>
<div class="form-group">
<label for="email">E-mail</label>
<?php echo $emailerror ?>
<input style="width: 180px" type="email" id="email" name="email" class="form-control" placeholder="E-mail">
</div>
<hr />
<div class="radiogroup">
<label for="radiogroup"> Bees on campus? </label>
<label class="radio-inline">
<input type="radio" name="vote" id="voteyesradio" value="yes" checked>
Yes
</label>
<label class="radio-inline">
<input type="radio" name="vote" id="votenoradio" value="no">
No
</label>
</div>
<div class="form-group">
<input type="submit" name="submit" id="submitButton" class="btn btn-success btn-block" value="Vote!"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
This is the JS code:
$(".contentContainer").css("min-height", $(window).height());
$("#image").css("min-height", $("#beeweek").height());
$(document).ready(function () {
$("#submitButton").click(function () {
$("#myModal").modal('show');
})
});
$(".video-container").css("min-height", $(window).height());
If you don't want the page being refreshed, you should submit your form using Ajax, this link should help you, jQuery Ajax POST example with PHP

Ajax callback only applying to top div in list of jquery form groups

Hello smarter people,
So as the title conveys, i'm having some difficulties, and I've wasted a good 8 hours trying to figure it out :)
I posted a Question earlier, to which I got no answers. I was having difficulties with my ajax, and it's interaction with a form. This form is in an admin panel, and is for dynamically creating and editing navigation links on the front end of my (hopefully) soon-too-be site.
My problem specifically is: I am unable to, via ajax, have the text-content of the anchor tag (which causes the form to dropdown), to immediately reflect on screen...
http://i1379.photobucket.com/albums/ah126/conchairtoe/3_zpsb897a6a4.png
As you can see, the ajax has run, no errors, yet the label (anchor tag for enacting drop-down form) remains "test", when I typed "testing!!!!!!" in.
Everything behind the scenes worked, as the database successfully updates the corresponding data, and so does the anchor tag text once i reload the page, but that ain't very ajaxy now is it!
Here's the Javascript for when the form is submitted.
// NAV ITEM FORM - UPDATE / SUBMIT
$(".nav-form").submit(function(event) {
var navData = $(this).serializeArray(); // The serializeArray( ) method serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with.
var navLabel = $('input[name=label]').val();
var navID = $('input[name=id]').val();
$.ajax({
url: "ajax/navigation.php",
type: "POST",
data: navData
}).done(function(){
$("#label_"+navID).html(navLabel);
}); // END $.ajax
alert("navID = "+navID+" navLabel = "+navLabel);
event.preventDefault(); // will prevent form from submitting
});//END nav-form
Please note the .done callback.
I've narrowed the problem down!
The ajax works ONLY on whichever of the sortable anchors is in position 1 (the top of the list) - for when I change the "Home Page", or, again, which ever one I happen to move to the top of the list, the label updates immediately as per the ajax.
As you can see in the code, I have those alerts to verify this:
http://i1379.photobucket.com/albums/ah126/conchairtoe/final_zps7a7ddc68.png
Here is the code for the DOM environment
Navigation
<div class="row">
<div class="col-md-3">
<ul id="sort-nav" class="list-group-item">
<!--EXISTING NAV-ITEMS-->
<?php
$query = "SELECT * FROM navigation ORDER BY position ASC";
$result = mysqli_query($dbc, $query);
while ($list = mysqli_fetch_assoc($result)) { ?>
<li id="list_<?php echo $list['id']; ?>" class="list-group-item">
<a id="label_<?php echo $list['id']; ?>" data-toggle="collapse" data-target="#form_<?php echo $list['id']; ?>">
<?php echo $list['label']; ?> <i class="fa fa-chevron-down"></i>
</a>
<div id="form_<?php echo $list['id']; ?>" class="collapse">
<!--FORM-->
<form class="form-horizontal nav-form" role="form" action="index.php?page=navigation&id=<?php echo $list['id']; ?>" method="post">
<!-- ID -->
<div class="form-group">
<label class="col-sm-2 control-label" for="id">ID</label>
<div class="col-sm-10">
<input type="text" class="form-control input-sm" value="<?php echo $list['id'];?>" name="id" id="id" placeholder="ID - name" />
</div>
</div>
<!-- LABEL -->
<div class="form-group">
<label class="col-sm-2 control-label" for="label">Label</label>
<div class="col-sm-10">
<input type="text" class="form-control input-sm" value="<?php echo $list['label'];?>" name="label" id="label" placeholder="Label" />
</div>
</div>
<!--URL -->
<div class="form-group">
<label class="col-sm-2 control-label" for="value">URL</label>
<div class="col-sm-10">
<input class="form-control input-sm" type="text" value="<?php echo $list['url'];?>" name="url" id="url" placeholder="URL"></input>
</div>
</div>
<!--POSITION -->
<div class="form-group">
<label class="col-sm-2 control-label" for="value">Position</label>
<div class="col-sm-10">
<input class="form-control input-sm" type="text" value="<?php echo $list['position'];?>" name="position" id="position" placeholder="Position"></input>
</div>
</div>
<!-- STATUS -->
<div class="form-group">
<label class="col-sm-2 control-label" for="status">Status</label>
<div class="col-sm-10">
<input class="form-control input-sm" type="text" value="<?php echo $list['status'];?>" name="status" id="status" placeholder=""></input>
</div>
</div>
<!--Button and Hidden Input-->
<button type="submit" class="btn-btn-default">Save</button>
<input type="hidden" name="submitted" value="1" />
<input type="hidden" name="opened_id" value="<?php echo $list['id']; ?>" />
<span class="pull-right">
<a id="del_<?php echo $list['id']; ?>" class="btn btn-danger nav-item-delete" href="#" style="margin-bottom: 2px;" title="delete nav item"><i class="fa fa-trash"/></i></a>
</span>
</form> <!--END form-->
</div>
</li>
<?php } ?>
</ul>
</div>
<div class="col-md-9">
<div id="callback"><?php if(isset($message)) { echo $message; } ?></div>
</div> <!-- END col-md-12 -->
So yea, I truly apologize for my ignorance. Bare in mind that I barely could grasp css just 2 months ago or so.
THANK YOU SO MUCH FOR YOUR HELP IF YOU CAN PROVIDE IT.
Because you are not looking at the current form for the navID. The code $('input[name=id]') is using the first element it finds. You need to look at the form, use find().
var form = $(this);
var navData = form.serializeArray();
var navLabel = form.find('input[name=label]').val();
var navID = form.find('input[name=id]').val();

Categories