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.
Related
I'm working on a Bootstrap contact form with validation, the problem is I cannot get the PHP echo response to show on a specific DIV, after the form is sent, browser loads my contact.php file with the response. Is there any way to show the response on #success_message DIV on the same HTML? Here's my HTML:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Bootstrap 3 Contact form with Validation</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css'>
<link rel='stylesheet prefetch' href='http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.0/css/bootstrapValidator.min.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<form class="well form-horizontal" action="php/contacto.php" method="post" id="contact_form">
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label">Tu nombre</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="first_name" placeholder="¿Como te llamas?" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" >Tu apellido</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="last_name" placeholder="Tu apellido" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E-Mail</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="tucorreo#mail.com" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Teléfono</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input name="phone" placeholder="(55)1234-5678" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Tu comentario</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea rows="4" class="form-control" name="comment" placeholder="¡Cuéntanos como podemos ayudarte!"></textarea>
</div>
</div>
</div>
<!-- Success message -->
<div class="alert alert-success" role="alert" id="success_message">¡Listo!<i class="glyphicon glyphicon-thumbs-up"></i> Tu mensaje fue enviado, en breve nos pondremos en contacto contigo.</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4">
<button type="submit" class="btn btn-warning" >Enviar <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</fieldset>
</form>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.4.5/js/bootstrapvalidator.min.js'></script>
<script src="js/index.js"></script>
</body>
Here's my JS:
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
first_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: '¡Queremos saber tu nombre!'
}
}
},
last_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'Por favor, dinos tu apellido'
}
}
},
email: {
validators: {
notEmpty: {
message: 'Necesitamos una dirección de correo donde contactarte'
},
emailAddress: {
message: 'Tu dirección de correo no es válida'
}
}
},
phone: {
validators: {
notEmpty: {
message: 'Por favor, proporcionanos tu teléfono'
},
phone: {
country: 'MX',
message: 'Incluye un número de teléfono válido de 10 dígitos'
}
}
},
comment: {
validators: {
stringLength: {
min: 10,
max: 200,
message:'Please enter at least 10 characters and no more than 200'
},
notEmpty: {
message: 'Please supply a description of your project'
}
}
}
}
})
.on('success.form.bv', function(e) {
$('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
$('#contact_form').data('bootstrapValidator').resetForm();
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
console.log(result);
}, 'json');
});
});
And my PHP:
$EmailFrom = "contacto#tuka.mx";
$EmailTo = "manuel#tuka.mx";
$Subject = "Nuevo comentario en el website";
$first_name = Trim(stripslashes($_POST['first_name']));
$last_name = Trim(stripslashes($_POST['last_name']));
$email = Trim(stripslashes($_POST['email']));
$phone = Trim(stripslashes($_POST['phone']));
$comment = Trim(stripslashes($_POST['comment']));
// prepare email body text
$Body = "";
$Body .= "Nombre: ";
$Body .= $first_name;
$Body .= "\n";
$Body .= "Apellido: ";
$Body .= $last_name;
$Body .= "\n";
$Body .= "E-mail: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Teléfono: ";
$Body .= $phone;
$Body .= "\n";
$Body .= "Comentario: ";
$Body .= $comment;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
echo "<h2>¡Gracias! Recibimos tu mensaje</h2>";
}
else{
echo "<h2>Lo sentimos, hubo un error, inténtalo nuevamente</h2>";
}
?>
I have already uploaded it here, if you want to see it working:
http://tuka.mx/beta/contacto/index.html
The first parameter for .on() method must be event.
Here
.on('success.form.bv', function(e) {
Must be:
.on('submit', function(e) {
Looks something was wrong on JS, here's a solution:
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
submitHandler: function(validator, form, submitButton) {
$('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
$('#contact_form').data('bootstrapValidator').resetForm();
var bv = form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post(form.attr('action'), form.serialize(), function(result) {
console.log(result);
}, 'json');
},
fields: {
first_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: '¡Queremos saber tu nombre!'
}
}
},
last_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'Por favor, dinos tu apellido'
}
}
},
email: {
validators: {
notEmpty: {
message: 'Necesitamos una dirección de correo donde contactarte'
},
emailAddress: {
message: 'Tu dirección de correo no es válida'
}
}
},
phone: {
validators: {
notEmpty: {
message: 'Por favor, proporcionanos tu teléfono'
},
phone: {
country: 'MX',
message: 'Incluye un número de teléfono válido de 10 dígitos'
}
}
},
comment: {
validators: {
stringLength: {
min: 10,
max: 200,
message:'Please enter at least 10 characters and no more than 200'
},
notEmpty: {
message: 'Please supply a description of your project'
}
}
}
}
})
});
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) {
........
This is my website: http://bbb.antalyabalikcilik.com.tr/contact-us.html
I have a contact form. I get emails to my email address but the form doesn't show up after email sending 'THANK YOU' alert.
html code:
<!-- contact form -->
<div class='grid_col grid_col_8'>
<div class='ce clearfix'>
<h3 class="ce_title">Drop us a line</h3>
<div>
<div role="form" class="cf" id="cf-f16-p10-o1" lang="en-US" dir="ltr">
<div class="screen-reader-response"></div>
<form action="email.php" method="post" class="cf-form contact-form" novalidate="novalidate">
<p>Name*
<br />
<span class="cf-form-control-wrap your-name"><input type="text" name="name" value="" size="107" class="cf-form-control cf-text cf-validates-as-required" aria-required="true" aria-invalid="false" />
</span>
</p>
<p>Email*
<br />
<span class="cf-form-control-wrap your-email"><input type="email" name="email" value="" size="107" class="cf-form-control cf-text cf-email cf-validates-as-required cf-validates-as-email" aria-required="true" aria-invalid="false" />
</span>
</p>
<p>Message
<br />
<span class="cf-form-control-wrap your-message"><textarea name="message" cols="107" rows="8" class="cf-form-control cf-textarea" aria-invalid="false"></textarea>
</span>
</p>
<p>
<input type="submit" value="Gönder" class="cf-form-control cf-submit" />
</p>
<div class="cws_msg_box error-box clearfix">
<div class="icon_section"><i class="fa fa-exclamation"></i></div>
<div class="content_section">
<div class="msg_box_title">Error box</div>
<div class="msg_box_text"></div>
</div>
</div>
</form>
<div class="email_server_responce"></div>
</div>
</div>`enter code here`
</div>
</div>
<!-- / conatct form -->
email.php
<?php
$name = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "mail.xxx.com."; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "xxx#xxx.com"; // SMTP username
$mail->Password = "123456789"; // SMTP password
$mail->From = "xxx#xxx.com";
$mail->FromName = "www.xxx.com";
$mail->AddAddress("xxx#hotmail.com");
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "received from website email";
$mail->Body = $message;
$mail->AltBody = $message;
$content = '<div style="background: #eee; padding: 10px; font-size: 14px; font-family: comic sans ms">
İsim : '.$name.'<br />
Email : '.$email.'<br />
Mesaj : '.$message.'</div>';
$mail->MsgHTML($content);
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
js code:
/* contact form */
if (jQuery(".contact-form").length) {
/**/
/* contact form */
/**/
/* validate the contact form fields */
jQuery(".contact-form").each(function(){
jQuery(this).validate( /*feedback-form*/{
onkeyup: false,
onfocusout: false,
errorElement: 'p',
errorLabelContainer: jQuery(this).find('.msg_box_text'),
rules:
{
name:
{
required: true
},
email:
{
required: true,
email: true
},
message:
{
required: true
},
verify: {
required: true,
remote: {
url: 'php/check-capcha.php',
type: "post",
data:
{
code: function()
{
return jQuery('.verify').val();
}
}
}
}
},
messages:
{
name:
{
required: 'Please enter your name',
},
email:
{
required: 'Please enter your email address',
email: 'Please enter a VALID email address'
},
message:
{
required: 'Please enter your message'
},
verify: {
required: 'Please enter Captcha',
remote: "Please enter a VALID Captcha"
}
},
invalidHandler: function()
{
jQuery(this).find(".cws_msg_box.error-box").slideDown('fast');
jQuery("#feedback-form-success").slideUp('fast');
},
submitHandler: function(form)
{
jQuery(form).find(".cws_msg_box.error-box").slideUp('fast');
var $form = jQuery(form).ajaxSubmit();
submit_handler($form, jQuery(form).parent().children(".email_server_responce") );
}
});
})
/* Ajax, Server response */
var submit_handler = function (form, wrapper){
var $wrapper = jQuery(wrapper); //this class should be set in HTML code
$wrapper.css("display","block");
var data = {
action: "email_server_responce",
values: jQuery(form).serialize()
};
//send data to server
jQuery.post("email.php", data, function(s_response) {
s_response = jQuery.parseJSON(s_response);
if(s_response.info == 'success'){
$wrapper.addClass("message message-success").append('<div class="cws_msg_box success-box clearfix"><div class="icon_section"><i class="fa fa-thumbs-up"></i></div><div class="content_section"><div class="msg_box_title">Success!</div><div class="msg_box_text">Your message was successfully delivered.</div></div></div>');
$wrapper.delay(5000).hide(500, function(){
jQuery(this).removeClass("message message-success").text("").fadeIn(500);
$wrapper.css("display","none");
});
jQuery(form)[0].reset();
} else {
$wrapper.addClass("cws_msg_box error-box clearfix").append("<div class='icon_section'><i class='fa fa-exclamation'></i></div><div class='content_section'><div class='msg_box_title'>Server fail!</div><div class='msg_box_text'><p> Please try again later!</p></div></div>");
$wrapper.delay(5000).hide(500, function(){
jQuery(this).removeClass("cws_msg_box error-box clearfix").text("").fadeIn(500);
$wrapper.css("display","none");
});
}
});
return false;
}
}
/**/
What is wrong?Please help me...
after implementing a jquery form validation and redirecting with function btn_onclick()
{ window.location.href = "http://localhost/loginprivate.php";} from index.php to loginprivate.php my webapps php script wont be executed. The user become trough a javascript function and window.location.href from index.php redirected loginprivate.php you can see here. After the first pageload the page become loaded again with <script src="loadagain.js"></script> this works fine too.
Now the problem is that if I click the submit button the php code wont become executed, that can I see because no cookies become created, and the user become redirected to index.php.
my php code:
if(isset($_POST["submit"]))
{
$hostname='localhost';
$username='root';
$password='';
unset($_POST['password']);
$salt = '';
for ($i = 0; $i < 22; $i++) {
$salt .= substr('./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', mt_rand(0, 63), 1);
}
$_POST['password'] = crypt($_POST['password'],'$2a$10$'.$salt);
$new = 0;
try {
$dbh = new PDO("mysql:host=$hostname;dbname=search",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO users (username, password)
VALUES ('".$_POST["username"]."','".$_POST["password"]."')";
if ($dbh->query($sql)) {
echo "New Record Inserted Successfully";
}
else{
echo "Data not successfully Inserted.";
}
$new = $dbh->lastInsertId();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if ($new > 0)
{
$t = time() + 60 * 60 * 24 * 1000;
setcookie("username", $_POST['username'], $t);
setcookie("userid", $new , $t);
}
else
{
}
}
my html code:
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" href="themes/my-costum-theme.min.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<!-- Einstellungen zur Defintion als WebApp -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="loadagain.js"></script>
<script>
$(document).ready(function () {
$('#myform').ajaxForm();
$('#myform').validate({ // initialize the plugin
rules: {
username: {
required: true,
minlength: 2,
maxlength: 30
},
password: {
required: true,
minlength: 3,
maxlength: 30
}
},
submitHandler: function (form) { // for demo
$.ajax({
type: 'post',
url: 'loginprivate.php' //url where you want to post the stuff.
data:{
username: 'root',
password: 'maxicora123'
},
success: function(res){
//here you will get res as response from php page, either logged in or some error.
window.location.href = "http://localhost/loc/main.php";
}
});
return false; // for demo
}
});
});
</script>
</head>
<body>
<div class="ui-page" data-theme="b" data-role="page">
<div data-role="header"><h1>localcorps</h1></div>
<div id="wrapper1" style=" width: 90%; padding-right:5%; padding-left:5%" name="wrapper1">
<form name="login-form" id="myform" class="login-form" action="./loginprivate.php" method="post">
<div class="header1"></div>
<div class="content1">
<div data-role="fieldcontain">
<label for="username">Username:</label>
<input name="username" type="text" class="input username" id="username"/>
</div>
</div>
<div data-role="fieldcontain">
<label for="password">Password:</label>
<input name="password" type="password" class="input password" id="password"/>
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button"/>
</div>
</form>
</div>
</div>
</div>
</body>
According to your comment, I get now only this "Array ( )" on my screen. it means that you ain't posting anything to PHP page.
That's just because, you're redirecting the control to PHP page instead of submitting the form.
so, you can validate the code using jQuery and on successful validation do a ajax post request instead of shifting the control.window.location.href = "http://localhost/lak/main.php";
instead of shifting control, do a post.
$.ajax({
type: 'post',
url: 'loginprivate.php' //url where you want to post the stuff.
data:{
username: 'someUserName',
password: 'xxxxxxxxxxxx'
},
success: function(res){
//here you will get res as response from php page, either logged in or some error.
//and if you're logged in successfully, redirect here now.
}
});
Hope this will help.
I am using bootbox modal for calling a modal form but form is not appeared as a modal. Nothing happens when we click compose. I want to open a form in a model after clicking the compose button but its not working.
<a class="btn btn-block btn-compose btn-lg" id="loginButton"><i class="fa fa-" ></i> Compose Mail </a>
<!-- The login modal. Don't display it initially -->
<form id="loginForm" method="post" class="form-horizontal" style="display: none;">
<div class="form-group">
<label class="col-xs-3 control-label">To</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="to" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Subject</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="ssubject" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Message</label>
<div class="col-xs-5">
<textarea name="smessage" class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-default">Send</button>
</div>
</div>
</form>
This is html form and the java script file are placed in same page inbox.php
$(document).ready(function() {
$('#loginForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
to: {
validators: {
notEmpty: {
message: 'Please type destination bo'
}
}
},
ssubject: {
validators: {
notEmpty: {
message: 'Please type subject'
}
}
},
smessage: {
validators: {
notEmpty: {
message: 'Please type some message'
}
}
}
}
});
// Login button click handler
$('#loginButton').on('click', function() {
bootbox
.dialog({
title: 'Compose Message',
message: $('#loginForm'),
show: true // We will show it manually later
})
.on('shown.bs.modal', function() {
$('#loginForm')
.show() // Show the login form
.formValidation('resetForm', true); // Reset form
})
.on('hide.bs.modal', function(e) {
// Bootbox will remove the modal (including the body which contains the login form)
// after hiding the modal
// Therefor, we need to backup the form
$('#loginForm').hide().appendTo('body');
})
.modal('show');
});
});
</script>
<script>
$(document).ready(function() {
$('#loginForm').on('success.form.fv', function(e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
validator = $form.data('formValidation'),
username = validator.getFieldElements('username').val();
// Hide the modal containing the form
$form.parents('.bootbox').modal('hide');
// Show the welcome dialog
// Use Ajax to submit form data
$.ajax({
//url: $form.attr('action'),
url: 'test/send.php',
type: 'POST',
data: $form.serialize(),
success: function(result) {
//alert(result);
//bootbox.alert('Welcome back, ' + username);
bootbox.alert(result);
window.location.reload();
}
});
});
});
</script>
and here's the test/send.php code.
<?php
$from="0";
$to=$_POST["to"];
$subject=$_POST["ssubject"];
$message=$_POST["smessage"];
//echo $to.$message;
//validate before insert
if(strlen($subject)>50){
echo "Subject was too long";
die();
}
if(strlen($message)>150){
echo "Message was too long";
die();
}
include('../dbsource.php');
$mysqli=connect();
if(insert($mysqli,$from,$to,$subject,$message)>0)
echo "Message was sent";
else
echo "Message was not sent";
?>
<?php
function insert($mysqli,$from,$to,$subject,$message){
$mdate=date('Y-m-d');
$mtime=date('H:i:s');
$query = "INSERT INTO messages (mfrom,mto,subject,message,mdate,mtime)".
"VALUES ('$from','$to','$subject','$message','$mdate','$mtime')";
if($mysqli->query($query)>0)
return($mysqli->insert_id);
else
return 0;
}
?>
The modal does not appear.
I dont know why is the modal is not appearing in this project.
Can anybody help me ?
error in console: