Captcha is not validating in jquery side..! - javascript

I am using php to validate the google REcaptcha..As far as the back-end validation gose is working out fine it giving error if captcha not submitted and if done user is stored in database but major problem arises when i connect it with jquery...thing is it is always giving out error "your missing captcha" every time even if captcha is validated in back-end, please help me out of this, pardon me if am wrong..!!
here gose .php file
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
/*
if required include seperate validation
*/
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
/*
validation process
starts from here
*/
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate your password
if(strlen($password) >= 6){
//validate your mobile
if(strlen($mobile) == 12){
//validate captcha
//your site secret key
$secret = 'XXXX_secret-key_XXXX';
if(isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['recaptchaResponse'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
//Check for valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
}elseif($db->isMobileNumberExisted($mobile)) {
//user already existed
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
}else{
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
}else{
//failed to submit captcha
$response["error"] = true;
$response["error_msg"] = "Sorry this application is not for bots";
echo json_encode($response);
}
}else{
//failed to submit captcha
$response["error"] = true;
$response["error_msg"] = "your missing captcha";
echo json_encode($response);
}
}else{
//invalid mobile number
$response["error"] = true;
$response["error_msg"] = "Mobile number is invalid!";
echo json_encode($response);
}
}else{
//min of 6-charecters
$response["error"] = true;
$response["error_msg"] = "password must be of atleast 6-characters!";
echo json_encode($response);
}
}else{
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
}else{
//missing the required fields
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
Here gose .html file in bootstrap
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MiiSKy | Register</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src = "register.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<link href="css/plugins/iCheck/custom.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body class="gray-bg">
<div class="middle-box text-center loginscreen animated fadeInDown">
<div>
<div>
<!--<h3 class="logo-name">MiiSky</h3>-->
<img src="img/landing/mii-logo.png">
</div>
<!--<h3>Register to MiiSky</h3>-->
<p>Create account to see it in action.</p>
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
</div>
<div class="form-group" id="recaptcha_widget">
<div class="required">
<div class="g-recaptcha" data-sitekey="XXXXX_site-key_XXXXXX"></div>
<!-- End Thumbnail-->
</div>
</div>
<button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
</form>
here gose the main .js file
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
var recaptchaResponse = grecaptcha.getResponse();
var status = $('form')[0].checkValidity();
if(status){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "process.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val(),
recaptchaResponse: recaptchaResponse
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
grecaptcha.reset();
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
$('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});

First of all make sure that you've included the necessary JavaScript resource to render reCAPTCHA widget properly, like this:
<html>
<head>
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
Here's the reference:
Displaying the widget
Now comes to your user's response. The response from the user's captcha challenge can be fetched in three ways. It can be as,
g-recaptcha-response - a POST parameter in the submitted form
grecaptcha.getResponse(widget_id) - will provide the response after the user completes the captcha.
A string argument to the callback function specified in the config object passed to the render method.
Here's the reference:
Verifying the user's response
For you purpose use grecaptcha.getResponse() to get the user's response.
And as a sidenote use grecaptcha.reset() to ask the end user to verify with reCAPTCHA again. From the manual:
If your website performs server side validation using an AJAX request, you should only verify the user’s reCAPTCHA response token (g-recaptcha-response) once. If a verify attempt has been made with a particular token, it cannot be used again. You will need to call grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
Here's your HTML code:
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
</div>
<div class="form-group" id="recaptcha_widget">
<div class="required">
<div class="g-recaptcha" data-sitekey="XXXXXX_SITE-KEY_XXXXXXX"></div>
<!-- End Thumbnail-->
</div>
</div>
<button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>
</form>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
Your jQuery should be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
var recaptchaResponse = grecaptcha.getResponse();
var status = $('form')[0].checkValidity();
if(status){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "process.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val(),
recaptchaResponse: recaptchaResponse
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
grecaptcha.reset();
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
$('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
And finally your PHP should be like this:
<?php
// your code
//your site secret key
$secret = 'XXXXXXX_Secret-key_XXXXXXX';
if(isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['recaptchaResponse'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
}else{
// failure
}
}
// your code
?>

Related

How to get the success message in the same page after submitting the form?

I'm trying to display a success and error message in the same page. What do i need to change?
The form is to send the data to the database and then show a success message in the same page, then redirect to another page. I've tried changing the ID value in the form and the java script, i still get the same results, the data is sent to the database, it redirects to another page, but it doesn't show the success message before redirecting.
Controller:
public function register_ajax() {
//form validation rules
$this->form_validation->set_rules('org_name', 'Organisation Name',
'trim|required');
$this->form_validation->set_rules('email', 'Email',
'trim|required|valid_email|is_unique[new_church.email]',
array('is_unique' => "This email address is already registered
with this application.")
);
$this->form_validation->set_rules('password', 'Your Password',
'trim');
$this->form_validation->set_rules('c_password', 'Confirm Password',
'trim|required|matches[password]',
array(
'matches' => 'Password does not match'
)
);
if ($this->form_validation->run()) {
$this->registration_model->update_church(); //insert the data
into db
echo 1;
redirect(site_url('registration/payment'));
} else {
echo validation_errors();
}
}
Model:
public function update_church() {
$org_name = ucwords($this->input->post('org_name', TRUE));
$email = $this->input->post('email', TRUE);
$password = ucfirst($this->input->post('password', TRUE));
$c_password = ucfirst($this->input->post('c_password', TRUE));
$data = array (
'org_name' => $org_name,
'email' => $email,
'password' => $password,
'c_password' => $c_password,
);
$this->db->insert('new_church', $data);
//email admins
//$this->notify_admins($name, $email, $subject, $message);
}
JavaScript:
//Registration
$('#registration_form').submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: base_url + 'registration',
type: 'POST',
data: form_data,
success: function(msg) {
if (msg == 1) {
$('#status_msg').html('<div class="alert alert-success
text-center"> Success.</div>').fadeIn( 'fast' );
$('#registration_form')[0].reset(); //reset form fields
} else {
$('#status_msg').html('<div class="alert alert-danger
text-center">' + msg + '</div>').fadeIn( 'fast' ).delay(
30000 ).fadeOut( 'slow' );
}
}
});
});
View:
<?php
$form_attributes = array("id" => "registration_form");
echo form_open('registration/register_ajax', $form_attributes); ?>
<div class="login100-form validate-form">
<div class="wrap-input100 validate-input" data-validate = "First
name is required">
<label class="form_header">Organisation Name</label>
<input class="input100" type="text" name="org_name" value="<?php
echo set_value('org_name'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Valid
email is required: ex#abc.xyz">
<label class="form_header">Your Work Email Address</label>
<input class="input100" type="email" name="email" value="<?php
echo set_value('email'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Password
is required">
<label class="form_header">Your Password</label>
<input class="input100" type="password" name="password" value="<?
php echo set_value('password'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Confirm Password">
<label class="form_header">Confirm Password</label>
<input class="input100" type="password" name="c_password" value="<?php echo set_value('c_password'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="text-center p-t-12">
<p>By clicking the button below, you agree to StreamApp's terms of acceptable use</p>
</div>
<div class="m-t-20">
<div id="status_msg"></div>
</div>
<div class="container-login100-form-btn">
<button class="login100-form-btn"> NEXT </button>
</div>
</div>
<?php echo form_close(); ?>
I expect a success message to appear before redirecting to another page
what happened to your code is when your try to run the form validation it get always true because you set a condition where not executing if the result is true or false.
if ($this->form_validation->run() == TRUE) { //you should change it to this
$this->registration_model->update_church();
$data['success'] = 1;
} else { //if the form validation run false it will display the error.
$data['error'] = validation_errors();
}
echo json_encode($data);
And if you are going to send back a message to your AJAX code you should encode it first using JSON.
To display it.. do this.
if (msg.success == 1) {
$('#status_msg').html('<div class="alert alert-success
text-center"> Success.</div>');
$('#registration_form')[0].reset(); //reset form fields
setTimeout(function(){
window.location.replace("<?php echo base_url('registration/payment') ?>");
}, 3000); //set it to your time
} else if(msg.error){
$('#status_msg').html('<div class="alert alert-danger
text-center">' + msg.error + '</div>').fadeIn( 'fast' ).delay(
30000 ).fadeOut( 'slow' );
}
Hope that helps.Let me know the result.
Remove this line:
redirect(site_url('registration/payment'));
And in your ajax success function add this:
if (response == "1") {
// todo set timeout maybe and show a success message then redirect.
window.location.href = siteUrl+"registration/payment";
}
And just make sure to define siteUrl in your js file:
const siteUrl = "http://localhost/";

Ajax not refreshing contact form (PHP and Bootstrap 4)

I have this exact code on another website and it works flawlessly but for some reason on this website it won't work. It sends the email but it refreshes the page and forwards it to a contact.php with a message.
I have read through everything I could find. I have gone over the code and nothing is different. I even changed the html button type from submit to button. Nothing is working. The last thing I tried was to copy and paste the code from the working website to this site, and still it refreshes the page.
The ajax codes is being loaded after the jquery.
html (index.html):
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages">
</div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">First Name *</label>
<input id="form_name" type="text" name="name" class="form-control" required="required"
<div class="help-block with-errors">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Last Name *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" required="required"
data-error="Lastname is required.">
<div class="help-block with-errors">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" required="required"
data-error="Valid email is required.">
<div class="help-block with-errors">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control">
<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 id="form_message" name="message" class="form-control" rows="4" required="required"
data-error="Please,leave us a message."></textarea>
<div class="help-block with-errors">
</div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-send" value="Send message">
</div>
</div>
</div>
</form>
php (contact.php)
<?php
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$from = 'Demo contact form <info#testing.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <info#testing.com>';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
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 just display the message
else {
echo $responseArray['message'];
}
?>
ajax (contact.js)
$(function () {
$('#contact-form').validator();
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "contact.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
my javascript files are in the following order:
<script src="js/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"
integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm"
crossorigin="anonymous"></script>
<script type="text/javascript" src="./js/mdb.min.js"></script>
<!--validator-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js"></script>
<!--contact.js-->
<script src="contact.js"></script>
Take out these changes:
Contact.php
// if requested by AJAX request return JSON response
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;
exit();
}
After echoing your json encoded array, it is important that you exit() the script else you won't end up with a proper JSON string on the client side;.
Contact.js
<script>
$(document).ready(function () {
$('.btn-send').on('click', function (e) {
e.preventDefault();
$('#contact-form').validator(); //Just make sure this works because I didn't work with it.
let url = "contact.php";
let formData = $("#contact-form").serialize();
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: formData, //You shouldn't use `this` inside this ajax scope if you are trying to refer to your form. It's better you call the form element by it's `id` here or reassign `this` before entering the ajax call scope.
success: function (data) {
// we recieve the type of the message: success x danger and apply it to the
let messageAlert = 'alert-' + data.type;
let messageText = data.message;
// let's compose Bootstrap alert box HTML
let alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
})
});
</script>
index.html
Everything thing is fine here. Just edit these lines:
<form id="contact-form" method="post" role="form">
<div class="col-md-12">
<input type="button" class="btn btn-send" value="Send message">
</div>

Can't redirect to another php page after I login, the login form reloades on the same page instead

Recently I've been facing this problem for a couple days. The login validation works perfectly. Unfortunately, I can't redirect to another page which is index.php after I try to login, and the login form is reloading on the same page at the bottom of the form instead, which is supposed to be for the error message just in case the user inputted the wrong username or password. Here are the screenshots of the form:
Screenshot of the login form at login.php
Screenshot of the login form when the user doesn't fill all the fields
Screenshot of the login form when the user inputted the wrong username or password
Screenshot of the login form after the user inputted the correct username and password, the form is reloading on the same page. Instead, I want it to redirect to another page, which is index.php
Here's my code:
login.php
<?php
require_once 'templates/header.php';
?>
<link rel="stylesheet" type="text/css" href="styles/login-style.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#login').click(function(){
var username = $('#usernameID').val();
var password = $('#passwordID').val();
$.post("classes/validation_login.php",{
user_val : username,
password_val : password,
},function(data){
if(data == 'success'){
window.location.href='index.php';
}else{
$('.error-message').html(data);
}
});
});
});
</script>
<title>Login</title>
<form id="login-form">
<h1>Login</h1>
<input type="text" id="usernameID" name="username" placeholder="Username" autocomplete="off"> <br>
<input type="password" id="passwordID" name="password" placeholder="Password" autocomplete="off"> <br>
<input type="button" id="login" name="register-button" value="Login">
</form>
<div class="error-message">
</div>
<?php
require_once 'templates/footer.php';
?>
validation_login.php
<?php
require_once '../core/init.php';
class validation_login{
private $username,$password;
public $errorMessage;
public function validate_login(){
$db = new database();
$this->username = input::get('user_val');
$this->password = input::get('password_val');
if(empty($this->username) || empty($this->password)){
$this->errorMessage = "Please fill all the fields!";
return false;
}else if(!$db->login()){
$this->errorMessage = "Invalid username or password!";
return false;
}else{
session::set('username',$this->username);
return true;
}
}
}
$login = new validation_login;
$login->validate_login();
echo "$login->errorMessage";
?>
Any help would be appreciated. Thank you!
You redirect within the ajax call. Thats the misstake.
Remove the AJAX call and add an action tag to the form. (to validation_login.php)
<form action="validate_login.php" method="post" id="login-form">
It is because you cannot redirect on the server side when using ajax, try returning a value and redirect base in the value, you can rewrite your code as below
validation_login.php
<?php
require_once '../core/init.php';
class validation_login{
private $username,$password;
public $errorMessage;
public function validate_login(){
$db = new database();
$this->username = input::get('user_val');
$this->password = input::get('password_val');
if(empty($this->username) || empty($this->password)){
$this->errorMessage = "Please fill all the fields!";
}else if(!$db->login()){
return false;
}else{
session::set('username',$this->username);
return true;
}
}
}
?>
login.php
<?php
require_once 'templates/header.php';
?>
<link rel="stylesheet" type="text/css" href="styles/login-style.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#login').click(function(){
var username = $('#usernameID').val();
var password = $('#passwordID').val();
$.post("classes/validation_login.php",{
user_val : username,
password_val : password,
},function(data){
if(data){
//means validation went through
//redirect user
window.location.href='index.php';
}else{
//validation returned false
//display error message
$('.error-message').html('incorrect Username or password');
}
});
});
});
</script>
<title>Login</title>
<form id="login-form">
<h1>Login</h1>
<input type="text" id="usernameID" name="username" placeholder="Username" autocomplete="off"> <br>
<input type="password" id="passwordID" name="password" placeholder="Password" autocomplete="off"> <br>
<input type="button" id="login" name="register-button" value="Login">
</form>
<div class="error-message">
</div>
<?php
require_once 'templates/footer.php';
?>

having trouble in showing php success message with ajax

Here is my below code I'm just trying to send a message form with php script but the message is submitted well. but when it comes to showing success message I'm having trouble page submits the data but shows no code.
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#send").click(function(event){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "process.php",
data:{
name: name,
email: email,
message: message,
},
success:function(data) {
$('#msg').html(data);
}
});
});
});
</script>
Below is php and html code:
<?php
include 'db.php';
$name=$_POST["name"];
$email=$_POST["email"];
$message=$_POST["message"];
$query = mysqli_query($con, "INSERT INTO test(name, email, message) VALUES ('$name', '$email', '$message')");
if($query){
echo "Your message has been sent successfully!";
}
else{
echo "Your message has been not sent successfully!";
}
mysqli_close($con);
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="text" class="form-control" id="name" name="name">
<input type="text" class="form-control" id="email" name="email">
<textarea class="form-control" rows="5" id="message" name="message"></textarea>
<button id="send" type="submit" class="btn btn-primary">Send</button>
</form>
<div id="msg" class="alert alert-success hidden"><strong></strong></div>
It is because your form will be submitted as the button has the type submit. By changing the type to button the ajax should be working.
Change type="submit" to type="button"
I hope this will help!

Contact Form missing (send.php file)

Hi i would just like to ask some help regarding my contact form because I do not know how to create a php script to run on submit my form (send.php). Here my code for the Contact Form:
<div class="contact_form_holder">
<form id="contact" class="row" name="form1" method="post" action="#">
<div class="span4">
<label>Nom</label>
<input type="text" class="full" name="name" id="name" />
</div>
<div class="span4">
<label>Email <span class="req">*</span></label>
<input type="text" class="full" name="email" id="email" />
<div id="error_email" class="error">Please check your email</div>
</div>
<div class="span8">
<label>Message <span class="req">*</span></label>
<textarea cols="10" rows="10" name="message" id="message" class="full"></textarea>
<div id="error_message" class="error">Please check your message</div>
<div id="mail_success" class="success">Thank you. Your message has been sent.</div>
<div id="mail_failed" class="error">Error, email not sent</div>
<p id="btnsubmit">
<input type="submit" id="send" value="Send" class="btn btn-large" /></p>
</div>
</form>
</div>
Here my Javascript:
$(document).ready(function(){
$("#send").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var error = false;
if(email.length == 0 || email.indexOf("#") == "-1" || email.indexOf(".") == "-1"){
var error = true;
$("#error_email").fadeIn(500);
}else{
$("#error_email").fadeOut(500);
}
if(message.length == 0){
var error = true;
$("#error_message").fadeIn(500);
}else{
$("#error_message").fadeOut(500);
}
if(error == false){
$("#send").attr({"disabled" : "true", "value" : "Loading..." });
$.ajax({
type: "POST",
url : "send.php",
data: "name=" + name + "&email=" + email + "&subject=" + "You Got Email" + "&message=" + message,
success: function(data){
if(data == 'success'){
$("#btnsubmit").remove();
$("#mail_success").fadeIn(500);
}else{
$("#mail_failed").html(data).fadeIn(500);
$("#send").removeAttr("disabled").attr("value", "send");
}
}
});
}
return false;
});
});
I'm guessing i need the url : "send.php", Thank you so much in advance.
you should give your action page where you are receiving your data. your code could be like this..
<form id="contact" class="row" name="form1" method="post" action="send.php">
First of all actually submits the surrounding form.
Use Because it does nothing next to submit.
Secondly in your ajax call you have written :
success: function(data){
if(data == 'success'){
$("#btnsubmit").remove();
$("#mail_success").fadeIn(500);
}
});
The if condition is invalid if the value of data is not 'success'. I don't know whether it is returning success or not.
So lastly change input type submit to input type button .. hope it will work..
Make a file name with "send.php" in the same root where it's html file exist.
and some php code here ...
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: webmaster#example.com" . "\r\n" .
//mail(to,subject,message,headers,parameters);
mail($email,$subject,$message,$headers);

Categories