Errors after form submission - javascript

A have a working form which being validated both in JavaScript/PHP .After submitting the form I got my success message , however if I filling same form after submission its shows me strange symbols errors when the field filled wrong,see attached 1: https://i.stack.imgur.com/uj73P.jpg
I am not sure whether its coming from PHP or Javascript.Please advise.
My form:
<section class="inspiration" id="three">
<div class="overlay">
<div class="container">
<div class="row">
<article class="col-md-12 text-center">
<div class="intermediate-container">
<div class="heading wow fadeInUp">
<h2>יש לכם שאלה? צרו איתי קשר</h2>
</div>
<div class="row">
<div class="col-md-3 col-sm-3"></div>
<div class="col-md-6 center-block col-sm-6 ">
<form id="mc-form" method="POST">
<div class="form-group col-xs-12 wow fadeInUp">
<label for="name" hidden>שם פרטי</label>
<input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי">
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 wow fadeInUp ">
<label for="phone" hidden>טלפון</label>
<input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון">
<span class='error-message' id='phone-error'></span>
</div>
<div class="form-group col-xs-12 wow fadeInUp">
<label for="email" hidden>דואר אלקטרוני</label>
<input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני">
<span class='error-message' id='email-error'></span>
</div>
<div class="form-group col-xs-12 wow fadeInUp ">
<label for="subject" hidden>נושא</label>
<input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא">
<span class='error-message' id='subject-error'></span>
</div>
<div class="form-group col-xs-12 wow fadeInUp">
<label for="message" hidden>הודעה</label>
<textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50"></textarea>
<span class='error-message' id='message-error'></span>
</div>
<!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
<button class="btn btn-custom-outline wow fadeInUp" id="submit-button">שלח</button>
<span class='error-message' id='submit-error'></span>
<span class="success">הודעתך נשלחה בהצלחה!</span>
</form>
</div>
</div>
</div>
</article>
</div>
</div>
</div>
</section>
My Javasript:
function sendForm() {
$('[id*="-error"]').text(''); // default hide all error messages
event.preventDefault(); // prevent form submission and therefore page reload
$.ajax({
type: 'POST',
url: './send.php',
data: $("#mc-form").serialize(),
success: function(data) {
if(data.hasOwnProperty('error')) {
Object.keys(data['error']).forEach(function(key) {
producePrompt(data['error'][key], key+'-error', 'red');
});
}
if(data.hasOwnProperty('mail_error')) {
alert('Could not send mail');
}
if(data.hasOwnProperty('success')) {
alert(data['success']);
$('.success').show();
$("#name").val('');
$("#phone").val('');
$("#email").val('');
$("#subject").val('');
$("#message").val('');
}
}
});
}
My PHP:
<?php
$error_msg = array();
$success_msg = array();
$data = '';
// prevent warnings or errors from displaying, else you won't get proper json result
ini_set('display_errors',0);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$error_msg['name'] = "שדה זה הינו חובה";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Zא-ת ]*$/",$name)) {
$error_msg['name'] = "אותיות ורווחים בלבד";
}
}
if (empty($_POST["email"])) {
$error_msg['email'] = "שדה זה הינו חובה";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_msg['email'] = "דואר אלקטרוני לא תקין";
}
}
if (empty($_POST["phone"])) {
$error_msg['phone'] = "שדה זה הינו חובה";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$error_msg['phone'] = "טלפון לא תקין";
}
}
if (empty($_POST["subject"])) {
$error_msg['subject'] = "שדה זה הינו חובה";
}
if (empty($_POST["message"])) {
$error_msg['message'] = "שדה זה בינו חובה";
}
if (empty($_POST["subject"])) {
$subject = "";
} else {
$subject = test_input($_POST["subject"]);
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if (empty($error_msg)){ // note that $lastname_error does not exists
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'XXXXXXXb#gmail.com';
$subjectm = 'Contact Form Submit';
$feedback = "שם: $name. טלפון: $phone. דואר אלקטרוני :$email. הודעה : $message";
if (mail($to, $subjectm, $feedback)){
$success_msg = "הודעתך נשלחה בהצלחה,תודה !";
$name = $email = $phone = $message = $subject = '';
} else {
$mail_error_msg = 'לא ניתן לשלוח אימייל';
}
}
// set output data accordingly
if(!empty($success_msg)) {
$data = array('success'=>$success_msg);
} else if(!empty($error_msg)) {
$data = array('error'=>$error_msg);
} else if(!empty($mail_error_msg)) {
$data = array('mail_error'=>$mail_error_msg);
}
// output json that you can parse with jquery
header('Content-Type: application/json');
echo json_encode($data);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
A have a working form which being validated both in JavaScript/PHP .After submitting the form I got my success message , however if I filling same form after submission its shows me strange symbols errors when the field filled wrong,see attached enter image description here
I am not sure whether its coming from PHP or Javascript.Please advise.

Related

How can I rewrite the HTML page to have the exact same fields?

I'm trying to make a new look for my website, but it looks like it doesn't want to login and I don't understand why.. Here's the original page:
<body class="jumbotron vertical-center" onload="redirect();">
<div class="container login-container">
<div class="row">
<div class="col-md-4 login-form mx-auto">
<h3>Login</h3>
<h6>Don't have an account? Register</h6>
<form>
<div class="error-message" id="errorMessage"></div>
<div class="form-group">
<input id="enterID" type="text" class="form-control" placeholder="Your User ID *" value="" required/>
</div>
<div class="form-group">
<input id="password" type="password" class="form-control" placeholder="Your Password *" value="" required/>
</div>
<div class="form-group">
<input class="btn btn-block btn-primary" value="Login" onclick="login();" readonly />
</div>
<div class="form-group">
Trouble logging in?
</div>
</form>
</div>
</div>
</div>
</body>
And here's the edited page:
<!-- To keep it in the center of page-->
<img class="wave" src="img/wave.png">
<div class="container_main">
<div class="img">
<img src="img/bg.svg">
</div>
<div class="login-content">
<form>
<img src="img/avatar.svg">
<h2 class="title">Quiz Website</h2>
<div class="input-div one">
<div class="i">
<i class="fas fa-user"></i>
</div>
<div class="div">
<input type="text" class="input" id="enterID" placeholder="Username">
</div>
</div>
<div class="input-div pass">
<div class="i">
<i class="fas fa-lock"></i>
</div>
<div class="div form-group">
<input id="password" type="password" class="form-control" placeholder="Password" value="" required/>
</div>
</div>
Don't have an account?
<div class="form-group">
Trouble logging in?
</div>
<input type="submit" class="btn" value="Login" onclick="login();" readonly >
<div class="error-message" id="errorMessage"></div>
</form>
</div>
</div>
</html>
What am I doing wrong? I don't want to use the body class jumbotron vertical-center cause it's making my website to look very awful.. I always get ,,XHR loading failed" and I don't understand why..
My checklogin.js file:
function login() {
var enterID = document.getElementById("enterID").value;
var password = document.getElementById("password").value;
if ((password != "") && (enterID != "")) {
var info = "?enterID=" + enterID + "&password=" + password;
$.ajax
({
type: "GET",
url: "php/login.php" + info,
success: function (respond) {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
} else {
document.getElementById("errorMessage").innerText = respond;
}
}
});
}
else {
document.getElementById("errorMessage").innerText = "Please fill in all the fields.";
}
}
function redirect() {
$.ajax
({
type: "GET",
url: "php/redirect.php",
success: function (respond) {
if (respond != "not logged.") {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
}
}
}
});
}
And my login.php file:
<?php
include "mysql-connect.php";
//get Info from login.html
$ID = $_GET['enterID'];
$PW = $_GET['password'];
$stmt = $connect->prepare("SELECT PW, userType, nickName FROM users WHERE ID = ?");
$stmt->bind_param("s",$ID);
$valid = $stmt->execute();
if (!$valid){
die("Could not successfully run query.". $connect->connect_error);
}
$result = $stmt->get_result();
if ($result->num_rows==0){
//display message of no such student/teacher/admin
echo "Failed to find an account with the input ID.";
} else {
$row = $result->fetch_assoc();
if (password_verify($PW, $row['PW'])) {
$type = $row['userType'];
$nick = $row['nickName'];
//var_dump($row['PW']);
//save data
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION["type"]=$type;
$_SESSION["userID"]=$ID;
$_SESSION["nickName"]=$nick;
//login success - Request.responseText to checklogin.js
echo $type;
} else {
//display message of password error
echo "The input password does not match the account password.";
}
}
$connect->close();
?>
And here's the redirect.php:
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_SESSION["type"])){
if ($_SESSION["type"] != $_SESSION["pageType"]){
$alert_message = "You cannot access this page using your account!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ if ('".$_SESSION["type"]."'=='admin'){ window.location.href = '../page/admin-system-management.php';} else if ('".$_SESSION["type"]."'=='student'){ window.location.href = '../page/student-dashboard.php';} else if ('".$_SESSION["type"]."'=='teacher'){ window.location.href = '../page/teacher-dashboard.php';} }, 0);</script>";
}
} else {
$alert_message = "Your login period has expired! Please login again!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ window.location.href = '$link'; }, 0);</script>";
}
?>

contactus form submit email dont send

I'm using a template website that is practically finished, but the form submit dont work.
Pls anyone can help me?
Here is my basic html:
<form action="#" class="form-contact" id="contactForm">
<div class="row">
<div class="col-sm-6 col-md-6">
<div class="form-group">
<input type="text" class="form-control" id="p_name" placeholder="* Nome" required="">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-6 col-md-6">
<div class="form-group">
<input type="email" class="form-control" id="p_email" placeholder="* Email" required="">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-6 col-md-6">
<div class="form-group">
<input type="text" class="form-control" id="p_phone" placeholder="* Telefone">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-6 col-md-6">
<div class="form-group">
<input type="text" class="form-control" id="p_subject" placeholder="* Assunto">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group">
<textarea id="p_message" class="form-control" rows="6" placeholder="* Mensagem"></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div id="success"></div>
<button type="submit" class="btn btn-primary">ENVIAR</button>
</div>
</form>
here is my form-process.php:
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// SUBJECT
if (empty($_POST["subject"])) {
$errorMSG .= "Subject is required ";
} else {
$subject = $_POST["subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "myemail#outlook.com";
$Subject = $subject;
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
Here is my ajax/javascript for sending the email:
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#p_name").val();
var email = $("#p_email").val();
var subject = $("#p_subject").val();
var message = $("#p_message").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&subject=" + subject + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#success").removeClass().addClass(msgClasses).text(msg);
}
I was never able to send a form, I always get the error "Did you fill in the form properly?"

Hide error text until box / button clicked on

I'm wanting the errName errEmail errMessage text to not be displayed until the user clicks on the Name, Email, or Message box. Also I'm wanting to not show $result until the submit button is pressed. As of right now it just displays the errName, errEmail, errMessage, and the alert even if the user is not interacting with the submit form.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
global $result;
if (isset($_POST["submit"])) {
$errName ="";
$errEmail ="";
$errMessage ="";
$result="";
$name = $_POST['name'];
$business = $_POST['business'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = '------';
$to = '-----';
$subject = 'Message from user on website';
$body ="-------";
}
// Check if name has been entered
if (!isset($_POST) || !key_exists('name', $_POST) || !filter_var($_POST['name'])) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST) || !key_exists('email', $_POST) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST) || !key_exists('message', $_POST) || !filter_var($_POST['message'])) {
$errMessage = 'Please enter your message';
}
// If there are no errors, send the email
if (!isset($errName) && !isset($errEmail) && !isset($errMessage)) {
$result .= '<br><div class="alert alert-success">Thank You! We will be in touch</div>';
} else {
$result .= '<br><div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
}
<div class="container" id="contact">
<div class="row">
<div class="col-md-6 col-md-offset-2">
<h1 class="page-header text-center">Email Form</h1>
<form class="form-horizontal" role="form" method="post" action="index.php#contact">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php showPost('name'); ?>">
<?php if (isset($errName)) {
echo "<p class='text-danger'>$errName</p>";
}?>
</div>
</div>
<div class="form-group">
<label for="business" class="col-sm-2 control-label">Business</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="business" name="business" placeholder="Business name" value="<?php showPost('business'); ?>">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="<?php showPost('email'); ?>">
<?php if (isset($errEmail)) {
echo "<p class='text-danger'>$errEmail</p>";
}?>
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea class="form-control" rows="4" name="message"><?php showPost('message');?></textarea>
<?php if (isset($errMessage)) {
echo "<p class='text-danger'>$errMessage</p>";
}?>
</div>
</div>
<div class="form-group text-xs-center">
<div style="margin: 0 auto" class="g-recaptcha" data-sitekey="----------"></div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
</div>
</div>
</form>
</div>
</div>
</div>```
You need to put all your php code inside if (isset($_POST["submit"])) ,because the condition !isset will always be true when you load your php page . Do below change in your code :
if (isset($_POST["submit"])) {
$errName ="";
$errEmail ="";
$errMessage ="";
$result="";
$name = $_POST['name'];
$business = $_POST['business'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = '------';
$to = '-----';
$subject = 'Message from user on website';
$body ="-------";
// Check if name has been entered
if (!isset($_POST) || !key_exists('name', $_POST) || !filter_var($_POST['name'])) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST) || !key_exists('email', $_POST) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST) || !key_exists('message', $_POST) || !filter_var($_POST['message'])) {
$errMessage = 'Please enter your message';
}
// If there are no errors, send the email
if (!isset($errName) && !isset($errEmail) && !isset($errMessage)) {
$result .= '<br><div class="alert alert-success">Thank You! We will be in touch</div>';
} else {
$result .= '<br><div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
}
} // end of isset

I have 2 forms in a webpage having same code but second form doesnot work

I have a webpage which contains 2 contact form one at the banner and another at the bottom of the webpage at contact details. I have being using php for this. However the mail gets submitted of the first form but not of the second form. But in case if I remove the first form from the website, the second form works absolutely fine. I would like to know the reason for it if any body can help. You can refer to website http://www.infinitesignalsolution.com
<form role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" required data-error="NEW ERROR MESSAGE">
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="sub" class="h4">Sub</label>
<input type="sub" id="sub" class="form-control" placeholder="Enter Subject" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="message" class="h4">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="btn btn-success btn-lg pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
JavaScript
$("#contactForm").validator().on("submit", function (event)
{
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm()
{
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var sub = $("#sub").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&sub=" + sub + "&message=" + message,
success : function(text)
{
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess()
{
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError()
{
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg)
{
if(valid){
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
PHP
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
if (empty($_POST["phone"])) {
$errorMSG = "Phone No is required ";
} else {
$phone = $_POST["phone"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailFrom = "info#infinitesignalsolution.com";
$EmailTo = "umar.neha06#gmail.com";
$Subject = "Enquiry received from website";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Phone: ";
$Body .= $phone;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$EmailFrom);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
Do both forms have the same ID? If so, give them unique ID's, but give them a common css class.
Then refer to $(".contactForm") instead. As for the fields, you can give them a class but target the correct ones using $(this).find('.field-class') inside the submit function.

Html form refuses to be submitted via JQuery

So I was following an AJAX/JQuery tutorial for a registration script that will be acted upon by PHP/MySQL and will be submitted via JQuery.
Now the problem that I'm encountering is that the form submits directly to the action page, which should not be so, as it supposed to submit to script.js Here are the html code for the form.
<form method="post" id="register-form" action="transact-user.php">
<h2 class="form-signin-heading"></h2>
<div class="form-group">
<div class='row'>
<div class='col-sm-6'>
<input type='text' class='form-control' id='fname' name='fname' placeholder="First name">
</div>
<div class='col-sm-6'>
<input type='text' class='form-control' id='lname' name='lname' placeholder="Last name">
</div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Phone Number" name = "phone" id = "phone" >
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name = "email" id ="email">
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name = "password" id = "password">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password Again" name = "confirmpassword" id = "confirmpassword">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block btn-apply" type="submit" name="btn-save" id = "btn-submit"><span class="glyphicon glyphicon-log-in"></span> Register</button>
</div>
</form>
</div> <!-- /container -->
<div id = "ack"></div>
script.js
$("button#btn-submit").click(function()
{ /* validation */
/* form submit */
if ($("fname").val()=="" || $("lname").val()=="" )
$("div#ack").html("Please enter both your first name and your surname");
else
$.post($("#register-form").attr("action"),
$("#register-form: input").serializeArray(),
function(data){
$("div#ack").html(data);
});
$("#register-form").submit(function(){
return false;
})
/* form submit */
});
Finally, this is the action php script transact-user.php
<?php
if($_POST)
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
if($email != '') {
$qry = "SELECT * FROM users WHERE email='$email'";
$result = mysqli_query($mysqli,$qry);
if($result) {
if(mysqli_num_rows($result) > 0) {
echo "Email already in use";
}
#mysqli_free_result($result);
}
else {
die("Query failed");
}
}
$activation = md5(uniqid(rand(), true));
if ($stmt = "INSERT INTO users(firstname, lastname, email, password, verification, phone)"
." values('$fname', '$lname', '$email', '$password', "
. "'$activation','$phone')" or
die("Could not perform query ".mysqli_error($mysqli))) {
$result = mysqli_query($mysqli, $stmt)
or die("The system could not register you"
. "".mysqli_error($mysqli) . "<br>" . $stmt);
if ($result){
echo "sent";
}
//echo "<a href=\"gethotel.php?hid=".$row['hotel_id'].
//
/* close statement */
//$stmt->close();
}
}
?>
The issue us because you are hooking to the click event of the submit button and are not preventing the event from completing.
Also note that your selector to build the querystring is incorrect, as there should be a space before the : and not between the : and input, eg $("#register-form :input")
To fix the issues hook to the submit event of the form and use preventDefault(). Try this:
$("#register-form").submit(function(e) {
e.preventDefault();
if ($("fname").val().trim() == "" || $("lname").val().trim() == "") {
$("div#ack").html("Please enter both your first name and your surname");
} else {
$.post(this.action, $(this).find(':input').serializeArray(), function(data) {
$("div#ack").html(data);
});
}
});

Categories

Resources