Bootstrap Jquery validation + PHP - javascript

I use Bootstrap validation with tooltips. I want to validate form (username, password) but the button (btn-login) isn't isset (returns NULL). It never goes to loop in PHP code (above). This is my code - HTML and JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register form</title>
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/formvalidation/0.6.1/css/formValidation.min.css"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/formvalidation/0.6.1/js/formValidation.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/formvalidation/0.6.1/js/framework/bootstrap.min.js"></script>
</head>
<body>
<div id="message"></div>
<form id="tooltipContainerForm" class="form-horizontal" method="post">
<div class="form-group">
<label class="col-xs-3 control-label">Full name</label>
<div class="col-xs-3">
<input type="text" class="form-control" name="username" placeholder="User name" />
</div>
<div class="col-xs-3">
<input type="password" class="form-control" name="password" placeholder="Password" />
</div>
</div>
<div class="form-group">
<div class="col-xs-9 col-xs-offset-3">
<button type="submit" class="btn btn-default" name="btn-login" id="btn-login">Validate</button>
</div>
</div>
</form>
<script>
$(document).ready(function() {
$('#tooltipContainerForm')
.formValidation({
framework: 'bootstrap',
err: {
container: 'tooltip'
},
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
username: {
validators: {
notEmpty: {
message: 'The first name is required and can not be empty'
}
}
},
password: {
validators: {
notEmpty: {
message: 'The last name is required and can not be empty'
}
}
},
}
})
.on('success.form.fv', function(e) {
e.preventDefault();
var $form = $(e.target),
fv = $form.data('formValidation');
var myData = $("#tooltipContainerForm").serialize();
alert(myData);
$.ajax({
url: "loginHandler.php",
type: 'POST',
data: myData,
success: function(result) {
if(result=="ok"){
$("#message").fadeIn(1000, function(){
$("#message").html('<div class="alert alert-success alert-dismissible fade in" role="alert" >'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">'+
'<span aria-hidden="true">×</span></button><strong>Success login!</strong> You have been successfully logged in. Redirecting in 2 seconds..</div>');
});
setTimeout(' window.location.href = "home.php"; ',2000);
}
else {
$("#message").fadeIn(1000, function(){
$("#message").html('<div class="alert alert-danger alert-dismissible fade in" role="alert" >'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">'+
'<span aria-hidden="true">×</span></button><strong>Something wrong!</strong> '+result+'</div>');
});
}
}
});
})
.on('err.field.fv', function(e, data) {
var $icon = data.element.data('fv.icon'),
title = $icon.data('bs.tooltip').getTitle();
$icon.tooltip('destroy').tooltip({
html: true,
placement: 'right',
title: title,
container: 'body'
});
});
});
</script>
</body>
</html>
This is my loginHadler.php. Into if it never goes.
<?php
require("functions.php");
session_start();
var_dump($_POST['btn-login']);
if(isset($_POST['btn-login'])){
$db = getDb();
//validate($_POST['user'], $db);
$passwordHash = sha1($_POST['password']);
$query = getSelectQuery("users","username",$_POST['username']);
$result = mysqli_query($db, $query);
if ($result) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if($row['password']==$passwordHash){
echo "ok";
$_SESSION['username'] = $row['username'];
} else {
echo "Username or password does not match.";
}
} else {
echo mysqli_error($db);
}
}

You cant check if a button isset. You can only check if the $_POST variables are set. do an isset($_POST['username'])

<?php
require("functions.php");
session_start();
var_dump($_POST['username']);
if(isset($_POST['username'])){
$db = getDb();
//validate($_POST['user'], $db);
$passwordHash = sha1($_POST['password']);
$query = getSelectQuery("users","username",$_POST['username']);
$result = mysqli_query($db, $query);
if ($result) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if($row['password']==$passwordHash){
echo "ok";
$_SESSION['username'] = $row['username'];
} else {
echo "Username or password does not match.";
}
} else {
echo mysqli_error($db);
}
}

You need to pass this btn to the data send from Ajax. Do something like this :
$.ajax({
url: "loginHandler.php",
type: 'POST',
data: {myData : myData, btn-login : "val"},
success: function(result) {
........

Related

Opening a .html with window.location

I'm writing a simple login page in Ajax + Jquery
I have an error when I click on the button. And I don't understand why.
Uncaught SyntaxError: Unexpected end of input
At this line
echo '<input type="button" value="connexion" OnClick="window.location.assign("http://localhost/loginmap/members/success.html")>';
There is my code
<?php
session_start();
//si le user a un session de ouverte
/*if(isset($_SESSION['connecté'])){
header('Location : success.html');
die();
}*/
if (isset($_POST['login'])) {
$connection = new mysqli('localhost','root','','monumap');
$email = $connection->real_escape_string($_POST['emailPHP']);
$password = $connection->real_escape_string($_POST['passwordPHP']);
$data = $connection->query("SELECT id FROM users WHERE email = '$email' AND password = '$password'");
if($data->num_rows >= 0) {//tout et ok -> connexion
$_SESSION['connecté'] = '1';
//$_SESSION['email'] = $email;
header('Location:'.$_SESSION['redirectURL']);
exit('<font color = "green">Connexion reussi...</font>');
}else{
exit('<font color = "red">Le Mot de passe / Email est inconnue </font>');
}
//exit($email . " = " . $password);
}
?>
<html>
<head>
<title>Monumap Connexion</title>
</head>
<body>
<form method="post" action="login.php">
<input type="text" id="email" placeholder="Email..."><br>
<input type="password" id="password" placeholder="Mot de passe..."><br>
<input type="submit" value="Log In" id="login">
</form>
<p id = "reponse"></p>
<div class="Bouton">
<?php if($_SESSION['connecté']==1){
echo '<input type="button" value="connexion" OnClick="window.location.assign("http://localhost/loginmap/members/success.html")>';
}
?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#login").on('click', function () {
var email = $("#email").val();
var password = $("#password").val();
if (email == "" || password == "")
alert('vos inputs sont vides');
else {
$.ajax(
{
url: 'login.php',
method: 'POST',
data: {
login: 1,
emailPHP: email,
passwordPHP: password
},
success: function (reponse) {
$("#reponse").html(reponse);
},
dataType: 'text'
}
);
}
});
});
</script>
</body>
</html>
echo '<input type="button" value="connexion" onclick="window.location.assign('."'http://localhost/loginmap/members/success.html'".');")/>';
It's cause you wrote quote character.
You can use this way as well.
echo '<input type="button" value="connexion" onclick="func()"/>';
?>
<script>
function func(){
window.location.assign("http://localhost/loginmap/members/success.html");
}
</script>

Disabled form submit button when textarea is empty

This is a wp front-end post submit the form. Title and content area is required to fill, if not submit button is not clickable. The required title is OK for me but I need to make content area optional. And I believe it's done by JavaScript
I can not find how to change text area to optional or what I found did not work. What should I change here
JavaScript:
* set validate form condition
*/
this.submit_validator = $("form#submit_question").validate({
rules : {
post_title : "required",
question_category : "required",
post_content : "required",
},
messages: {
post_title : qa_front.form_auth.error_msg,
question_category : qa_front.form_auth.error_msg,
post_content : qa_front.form_auth.error_msg,
}
});
if(ae_globals.user_confirm && currentUser.register_status == "unconfirm"){
AE.pubsub.trigger('ae:notification', {
msg: qa_front.texts.confirm_account,
notice_type: 'error',
});
return false;
}
if(currentUser.ID == 0){
AE.pubsub.trigger('ae:notification', {
msg: qa_front.texts.require_login,
notice_type: 'error',
});
Another JavaScript
// initialize modal question
initialize: function() {
this.blockUi = new AE.Views.BlockUi();
},
submitReport: function(event){
event.preventDefault();
var view = this,
form = $(event.currentTarget),
message = form.find('textarea#txt_report').val(),
data = form.serializeObject(),
$button = form.find("input.btn");
this.model.set('do_action', 'report');
this.model.save('data',data, {
beforeSend: function() {
if( message == '' ){
AE.pubsub.trigger('ae:notification', {
msg: qa_front.form_auth.error_msg,
notice_type: 'error',
});
return false;
}
view.blockUi.block($button);
},
success: function(result, status, jqXHR) {
view.blockUi.unblock();
if(status.success) {
view.closeModal();
AE.pubsub.trigger('ae:afterReport', {
msg: status.msg,
notice_type: 'success'
});
view.stopListening(AE.pubsub, 'ae:afterReport');
}
else{
AE.pubsub.trigger('ae:notification', {
msg: status.msg,
notice_type: 'error',
});
}
$("form#report_form")[0].reset();
},
});
},
setModel : function (model) {
this.model = model;
},
});
}
One more JavaScript:
cbUploaded: function(up, file, res) {
if (res.success == true) {
var textarea = $(upload_textarea);
var post_content = textarea.val();
$('.body-poll, .body-question').each(function(){
if(!$(this).hasClass('hide')){
console.log($(this).data('name'));
if($(this).data('name') == 'poll'){
tinymce.get('insert_poll').execCommand('mceInsertContent', false, "[img]" + res.data + "[/img]");
}else{
tinymce.get('post_content').execCommand('mceInsertContent', false, "[img]" + res.data + "[/img]");
}
}
})
post_content = post_content + '[img]'+ res.data +'[/img]';
textarea.val(post_content);
} else {
AE.pubsub.trigger('ae:notification', {
'notice_type' : 'error',
'msg' : res.msg
})
view.blockUi.unblock();
}
},
beforeSend: function() {
view.blockUi.block($upload_image_button);
},
success: function() {
view.blockUi.unblock();
}
});
},
/*
* Show notification
*/
showNotice: function(params) {
var view = this;
// remove existing notification
$('div.notification').remove();
var notification = $(view.noti_templates({
msg: params.msg,
type: params.notice_type
}));
FORM:
<?php
define( 'MOBILE_PATH', dirname(__FILE__) );
/**
*
* TEMPLATE FILTER QUESTIONS FOR MOBILE
* #author ThaiNT
* #since 1.0
*
**/
if( !function_exists('qa_mobile_submit_questions_form')){
function qa_mobile_submit_questions_form(){
global $current_user;
$role = get_user_role($current_user->ID);
$privi = qa_get_privileges();
?>
<section class="post-question-form-wrapper">
<div class="container no-padding">
<div class="tabs-title">
<ul>
<li><span class="title-bar-tab active" id="tab-question"><?php _e('Ask a Question', ET_DOMAIN);?></span></li>
<?php if(ae_get_option('poll_maker') !=="0") { ?>
<li><span class="title-bar-tab" id="tab-poll"><?php _e('Create a Poll', ET_DOMAIN);?></span></li>
<?php } ?>
</ul>
</div>
<div class="form-active-question">
<div class="body-question" data-name="question">
<form id="submit_question" action="">
<input type="hidden" id="qa_nonce" name="qa_nonce" value="<?php echo wp_create_nonce( 'insert_question' ); ?>">
<input id="add_tag_text" type="hidden" value="<?php printf(__("You must have %d points to add tag. Current, you have to select existing tags.", ET_DOMAIN), $privi->create_tag ); ?>" />
<div class="form-post">
<input type="text" name="post_title" id="question_title" placeholder="<?php _e("Your Question", ET_DOMAIN) ?>">
<span id="charNum"><?php echo ae_get_option('max_width_title', 150);?></span>
</div>
<div class="form-post">
<div class="select-categories-wrapper">
<div class="select-categories">
<option value=""><?php _e("Select Category",ET_DOMAIN) ?></option>
<?php
$terms = get_terms( 'question_category', array('hide_empty' => 0, 'orderby' => 'term_group' ) );
$value_type = 'slug';
foreach ($terms as $term) {
if($term->parent == 0){
if($value_type == 'slug') {
echo "<option value='".$term->slug."'>";
} elseif($value_type == 'id') {
echo "<option value='".$term->term_id."'>";
}
echo $term->name;
echo "</option>";
foreach ($terms as $value) {
if($term->term_id == $value->parent){
if($value_type == 'slug') {
echo "<option value='".$value->slug."'>";
} elseif($value_type == 'id') {
echo "<option value='".$value->term_id."'>";
}
echo "--".$value->name;
echo "</option>";
}
}
}
}
?>
</select>
</div>
</div>
</div>
<?php if(ae_get_option('ae_upload_images')){ ?>
<div class="form-post container_upload">
<div class="upload_image" id="mobile_images_upload_container">
<i class="fa fa-image"></i><?php _e("Insert Image", ET_DOMAIN); ?>
<span class="et_ajaxnonce" id="<?php echo wp_create_nonce( 'et_upload_images' ); ?>"></span>
<span id="mobile_images_upload_text">
<?php
global $max_file_size;
printf(__("Size must be less than < %sMB.", ET_DOMAIN),$max_file_size);
?>
</span>
</div>
</div>
<?php } ?>
<div class="form-post">
<textarea name="post_content" id="" cols="30" rows="10" placeholder="<?php _e("Your Description", ET_DOMAIN) ?>"></textarea>
</div>
<div class="form-post">
<input data-provide="typeahead" type="text" name="" id="question_tags" placeholder="<?php _e('Tag(max 5 tags)',ET_DOMAIN) ?>" />
</div>
<ul class="post-question-tags" id="tag_list"></ul>
<?php if(ae_get_option('gg_question_captcha') && $role != 'administrator'){ ?>
<div class="clearfix"></div>
<div class="container_captcha">
<div class="gg-captcha form-group">
<?php ae_gg_recaptcha(); ?>
</div>
</div>
<?php } ?>
<div class="group-btn-post">
<div class="container">
<div class="row">
<div class="col-xs-5 no-pad-left"><span class="text"><?php _e("Ask a Question", ET_DOMAIN) ?></span></div>
<div class="col-xs-7 text-right">
<button type="submit" class="submit-post-question"><?php _e("Submit", ET_DOMAIN) ?></button>
<?php _e("Cancel", ET_DOMAIN) ?>
</div>
</div>
</div>
</div>
</form>
</div>
<?php
/**

Contact form doesn't validate inside bootstrap modal

So I have made a contact form using the example at https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form which works fine when placed on a page, however when I place it inside a bootstrap popup modal, the validator doesn't work. If all fields are empty and submit button hit, it will say 'message sent' even though it did not send, and if you fill in the fields it will still send and give success message also.
Also, if I hit the button to open modal as soon as page loads but before the script has loaded, it will work, so it's obviously because the modal is not visible when the validator script loads, so it misses it.
If anyone has some answers it would be super helpful as I'm pretty new to PHP and JS!
Here is my modal HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header"><button aria-label="Close" class="close"
data-dismiss="modal" type="button"><span aria-hidden=
"true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form action="../contact.php" id="contact-form" method="post" name=
"contact-form">
<div class="messages"></div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_name">Firstname *</label>
<input class="form-control" data-error="Firstname is required." id="form_name"
name="name" placeholder="Please enter your first name" required="required"
type="text">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_email">Email *</label> <input class=
"form-control" data-error="Valid email is required." id="form_email" name=
"vemail" placeholder="Please enter your email" required="required" type=
"email">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_message">Message *</label>
<textarea class="form-control" data-error="Please,leave us a message." id=
"form_message" name="message" placeholder="Please enter your message" required=
"required" rows="4"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12"><input class="btn btn-success btn-send" type="submit"
value="Send message"></div>
</div>
</form>
</div>
</div>
<!-- /.modal-content --></div>
<!-- /.modal-dialog --></div>
<!-- /.modal -->
</body>
</html>
This is my PHP file
<?php
// configure
$from = '<mail#myemail.net>';
$sendTo = 'Demo contact form <mail#myemail.net>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'vemail' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
$email = ($_POST["vemail"]);
$subject2 = 'Thank you for contacting support.';
$msg = "Thank you for contacting Support. We have received your contact form and will be in contact as soon as possible";
$headers = 'Reply-To: mail#myemail.net' . "\r\n" ;
// let's do the sending
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($email, $subject2, $msg, $headers) && mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
?>
And JS
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "../contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
Put your ajax call inside the validation process and use submitHandler.
This answer by #Sparky might save your day https://stackoverflow.com/a/15625824/6952155
Please refer to this and edit to suit in your code.
$(document).ready(function () {
$("#contactform").validate({
ignore: ":hidden",
rules: {
name: {
required: true,
minlength: 3
},
cognome: {
required: true,
minlength: 3
},
subject: {
required: true
},
message: {
required: true,
minlength: 10
}
},
submitHandler: function (form) {
alert('valid form submission'); // for demo
$.ajax({
type: "POST",
url: "formfiles/submit.php",
data: $(form).serialize(),
success: function () {
$(form).html("<div id='message'></div>");
$('#message').html("<h2>Your request is on the way!</h2>")
.append("<p>someone</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='checkmark' src='images/ok.png' />");
});
}
});
return false; // required to block normal submit since you used ajax
}
});
});
Ondrej here, author of the tutorial on Bootstrapious.
I have just found out that there was an error in Bootstrap validator and it was not working correctly in combination with the Bootstrap modal.
The solution is downloading the latest version from https://github.com/1000hz/bootstrap-validator, currently 0.11.5.
Best,
Ondrej

submit button suddenly disabled when clicked

i am trying to insert simple username in database.
I wrote the code in bootstrap and then just copied it to netbeans and then insert php code in it.
Script is working well but when i am trying to submit to insert name in database, the submit button disabled and not giving any error or redirecting to another page.
Please help.
I am new on bootstrap.
<?php
include 'includes/db_connection.php';
if (isset($_POST['submit']))
{
//$name = filter_input(INPUT_POST, 'name',FILTER_SANITIZE_STRING);
//$firstname=filter_string('firstname');
$firstname = $_POST['firstname'];
$sql1 ="INSERT INTO student (firstname)
VALUES ('$firstname')";
$res1 = mysqli_query($conn, $sql1);
if($res1)
{
//$last_id = mysqli_insert_id($conn);
header("Location: successful_message.php");
//echo 'Successful';
// . " Last inserted ID is: " . $last_id;
}
else
{
header("Location: valid_test.php");
}
}
else{?>
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/ecmascript"></script>
<script src="http://formvalidation.io/vendor/formvalidation/js/formValidation.min.js"></script>
<link rel="stylesheet" href="http://formvalidation.io/vendor/formvalidation/css/formValidation.min.css">
<script src="http://formvalidation.io/vendor/formvalidation/js/framework/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<title>Form</title>
<!-- Bootstrap core CSS -->
<!-- Custom styles for this template -->
</head>
<body>
<form id="contactForm" method="post" action="validate-input.php" class="form-horizontal">
<div class="container-fluid">
<div class="container">
<div class="form-group">
<label class="col-xs-3 control-label">Full name</label>
<div class="col-xs-4">
<input type="text" class="form-control" name="firstname" placeholder="First name" />
</div>
<div class="form-group">
<div class="col-xs-9 col-xs-offset-3">
<button type="submit" value="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<?php } ?>
<script>
$(document).ready(function() {
// Generate a simple captcha
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function generateCaptcha() {
$('#captchaOperation').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' '));
}
generateCaptcha();
$('#contactForm')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
firstname: {
row: '.col-xs-4',
validators: {
notEmpty: {
message: 'The first name is required'
},
regexp: {
message: 'Name only contains Letter',
regexp: /^[A-Z a-z]*$/
}
}
},
lastName: {
row: '.col-xs-4',
validators: {
notEmpty: {
message: 'The last name is required'
}
}
},
phoneNumber: {
validators: {
notEmpty: {
message: 'The phone number is required'
},
regexp: {
message: 'The phone number can only contain the digits, spaces, -, (, ), + and .',
regexp: /^[0-9\s\-()+\.]+$/
}
}
},
email: {
validators: {
notEmpty: {
message: 'The email address is required'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
},
message: {
validators: {
notEmpty: {
message: 'The message is required'
},
stringLength: {
max: 700,
message: 'The message must be less than 700 characters long'
}
}
},
captcha: {
validators: {
callback: {
message: 'Wrong answer',
callback: function(value, validator, $field) {
var items = $('#captchaOperation').html().split(' '),
sum = parseInt(items[0]) + parseInt(items[2]);
return value == sum;
}
}
}
}
}
})
.on('err.form.fv', function(e) {
// Regenerate the captcha
generateCaptcha();
});
});
</script>
</div><!--End container -->
</div><!-- End container-fluid -->
</body>
</html>
remove action from your form
<form id="contactForm" method="post" class="form-horizontal">
you're validating to much on your script. remove other validation other than firstname
I tried it but still need to do it twice, so after submit, change the firstname again then submit again. didn't know is it because your code of the formvalidation.js
<?php
//include 'includes/db_connection.php';
if (isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$sql1 = "INSERT INTO student (firstname) VALUES ('$firstname')";
$res1 = mysqli_query($conn, $sql1);
if ($res1) {
echo 'succ';
// header("Location: successful_message.php");
} else {
echo 'fail';
// header("Location: valid_test.php");
}
} else {
?>
<script src="http://formvalidation.io/vendor/formvalidation/js/formValidation.min.js"></script>
<link rel="stylesheet" href="http://formvalidation.io/vendor/formvalidation/css/formValidation.min.css">
<script src="http://formvalidation.io/vendor/formvalidation/js/framework/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<title>Form</title>
</head>
<body>
<form id="contactForm" method="post" class="form-horizontal">
<div class="form-group">
<label class="col-xs-3 control-label">Full name</label>
<div class="col-xs-4">
<input type="text" class="form-control" name="firstname" placeholder="First name" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Pass</label>
<div class="col-xs-4">
<input type="text" class="form-control" name="password" placeholder="First name" />
</div>
</div>
<div class="form-group">
<div class="col-xs-9 col-xs-offset-3">
<button type="submit" value="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<?php } ?>
<script>
$(document).ready(function () {
// Generate a simple captcha
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function generateCaptcha() {
$('#captchaOperation').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' '));
}
generateCaptcha();
$('#contactForm')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
firstname: {
validators: {
notEmpty: {
message: 'The first name is required'
},
regexp: {
message: 'Name only contains Letter',
regexp: /^[A-Z a-z]*$/
}
}
},
password: {
validators: {
notEmpty: {
message: 'The password is required'
}
}
}
}
});
;
});
</script>
Above you are checking
if (isset($_POST['submit']))
{
instead of action="validate-input.php" write action=""
Leave action empty so that the form will be submitted to the
document's address, i.e. the same page.

JQuery/PHP form not Submiting

I have a site I'm working on Modestewebstudio.com
On the contact section of the site I have a form that I'm trying to submit using jQuery and pHp. For some reason the form does not submit. The validation works fine but whenever I hit submit nothing happens.
$(document).ready(function () {
$(window).load(function() { $("#load").fadeOut("slow"); });
var fadeInElement = function(id) {
$('#' + id).fadeIn();
};
//HOME-------------------------------------------------
$(".home").click(function () {
$('#about, #works, #contact').filter(":visible").fadeOut();
fadeInElement('home');
});
//ABOUT------------------------------------------------
$(".about").click(function () {
$('#home, #works, #contact').filter(":visible").fadeOut();
fadeInElement('about');
});
//WORKS------------------------------------------------
$(".works").click(function () {
$('#home, #about, #contact').filter(":visible").fadeOut();
fadeInElement('works');
});
//CONTACT----------------------------------------------
$(".contact").click(function () {
$('#home, #about, #works').filter(":visible").fadeOut();
fadeInElement('contact');
});
<!--//--><![CDATA[//><!--
$('form#contact-us').submit(function() {
$('form#contact-us .error').remove();
var hasError = false;
$('.requiredField').each(function() {
if($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Your '+labelText+' is missing.</span>');
$(this).addClass('inputError');
hasError = true;
} else if($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Your '+labelText+' is invalid.</span>');
$(this).addClass('inputError');
hasError = true;
}
}
});
if(!hasError) {
var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
$('form#contact-us').slideUp("fast", function() {
$(this).before('<p>Your email has been delivered!</p>');
});
});
}
return false;
});
//-->!]]>
//-----------------------------------------------------
});
<?php
error_reporting(E_ALL ^ E_NOTICE); // hide all basic notices from PHP
//If the form is submitted
if(isset($_POST['submitted'])) {
// require a name from user
if(trim($_POST['contactName']) === '') {
$nameError = 'Forgot your name!';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
// need valid email
if(trim($_POST['email']) === '') {
$emailError = 'Forgot to enter in your e-mail address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
// we need at least some content
if(trim($_POST['comments']) === '') {
$commentError = 'You forgot to enter a message!';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
// upon no failure errors let's email now!
if(!isset($hasError)) {
$emailTo = 'zenneson#gmail.com';
$subject = 'Submitted message from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
// set our boolean completion value to TRUE
$emailSent = true;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Denneson Modeste</title>
<!--Fonts-->
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Syncopate' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Special+Elite' rel='stylesheet' type='text/css'>
<!--CSS-->
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div id="load">
<div class="load-logo pulse"></div>
<p>Loading</p>
</div>
<div class="tv"></div>
<div class="home tv-btn">HOME</div>
<div class="about tv-btn">ABOUT</div>
<div class="works tv-btn">WORKS</div>
<div class="blog tv-btn">BLOG</div>
<div class="contact tv-btn">CONTACT</div>
<div id="home" class="channel">
<iframe width="100%" height="100%" src="https://www.youtube.com/embed/JdRO97mFMx8?rel=0&controls=0&autoplay=1&showinfo=0&disablekb=1&disablekb=1&modestbranding=1&start=7&loop=1&playlist=JdRO97mFMx8&wmode=opaque" frameborder="0" allowfullscreen></iframe>
</div><!-- end of home -->
<div id="about" class="channel">
<iframe width="100%" height="100%" src="https://www.youtube.com/embed/JdRO97mFMx8?rel=0&controls=0&autoplay=1&showinfo=0&disablekb=1&disablekb=1&modestbranding=1&start=7&loop=1&playlist=JdRO97mFMx8&wmode=opaque" frameborder="0" allowfullscreen></iframe>
</div><!-- end of about -->
<div id="works" class="channel">
</div><!-- end of works -->
<div id="contact" class="channel">
<div class="contact-border"></div>
<div class="stamp"></div>
<div class="contact-section">
<h3>Have a question or wanna say hello? Leave a message below.</h3>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<p class="info">Your message was sent and will be responded to ASAP.</p>
<?php } else { ?>
<form id="contact-us" action="contact.php" method="post">
<?php if(isset($hasError) || isset($captchaError) ) { ?>
<p class="alert">There was a mistake in the message</p>
<?php } ?>
<label>Name</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="txt requiredField" placeholder="Name:" />
<?php if($nameError != '') { ?>
<br /><span class="error"><?php echo $nameError;?></span>
<?php } ?>
<label>E-mail</label>
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="txt requiredField email" placeholder="Email:" />
<?php if($emailError != '') { ?>
<br /><span class="error"><?php echo $emailError;?></span>
<?php } ?>
<label>Message</label>
<textarea name="comments" id="commentsText" class="txtarea requiredField" placeholder="Message:"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if($commentError != '') { ?>
<br /><span class="error"><?php echo $commentError;?></span>
<?php } ?>
<button name="submit" type="submit" class="subbutton"> </button>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
</div><!-- end of contact-section -->
<?php } ?>
</div>
</div>
</div><!-- end of contact -->
<!--Javascript-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="js/application.js"></script>
</body>
</html>
Submitting the form results in the following error
404 (Not Found) http://modestewebstudio.com/contact.php
Make sure there that the file is in fact named contact.php, and that it's placed in the root directory of your web server.

Categories