i cant send a form data with ajax to php. It always refresh the page. Im using bootstrap modal to register form and i want to display error message (if have) on the top of form. Always refresh the page and if i again click to reg button to open the modal i see the error message. How i can do it without refresh the page? Any idea how can i do it?
form:
<?php echo display_error(); ?>
<form id="regform" class="form-signin" action="#" method="post">
<input type="text" id="username" class="form-control" placeholder="username" name="username" required autofocus>
<input type="email" id="email" class="form-control" placeholder="email" name="email"required autofocus>
<input type="password" id="pass1" class="form-control" placeholder="password" name="password_1" required>
<input type="password" id="pass2" class="form-control" placeholder="password again" name="password_2" required>
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" name="register_btn">Register</button>
</form>
js ajax
$('#register_btn').click(function(){
var data = {};
data.username = $('#username').val();
data.email = $('#email').val();
data.password_1 = $('#pass1').val();
data.password_2 = $('#pass2').val();
$.ajax({
type: "POST",
url: "functions.php",
data: data,
cache: false,
success: function (response) {
}
});
return false;
});
});
functions.php
include 'db_config.php';
session_start();
// connect to database
// variable declaration
$username = "";
$email = "";
$errors = array();
// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
register();
}
// REGISTER USER
function register(){
global $db, $errors;
// receive all input values from the form
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password_1']);
$password_2 = e($_POST['password_2']);
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$password')";
mysqli_query($db, $query);
$_SESSION['success'] = "New user successfully created!!";
header('location: home.php');
}else{
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$password')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
The JQuery selector you are using is using an ID, change the button from name="register_btn" to id="register_btn".
EDIT: Further looking at your code, you are missing the prevent default on the button, I would change the listener to the form instead and prevent default. The form is submitting to the current page which is the default behavior, which is why it looks like the page is just reloading.
See the below link for my code I use for form posts via AJAX:
http://aspintech.ca/journal/?entry_id=77
Related
I have a registration form using php, I'm checking the inputs with a validations and control the submitting form using ajax.
Everything works fine, except, after clicking submit button, Ajax loads the success result, in same registration form, and also not reload the page and redirect.
I want to reload and redirect register.php page to register.php?action=joined using Ajax form submit.
Before Ajax register.php have its own statement, if the registration succsessful ($_GET['action'] == 'joined')* its redirect and destroy the registration form and show success form.*
Please refer on the codes. Can someone help me how to figure this out.
registercontrol.php
<?php
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (! $user->isValidFullname($fullname)){
$infofn = 'Your name must be alphabetical characters';
echo '<p>'.$infofn.'</p>';
}
}
// If form has been submitted process it
if(isset($_POST['submit']) && $_POST['submit'] == 'register')
{
// Create the activasion code
$activasion = md5(uniqid(rand(),true));
try
{
// Insert into database with a prepared statement
$stmt = $db->prepare('INSERT INTO members (fullname) VALUES (:fullname, :email, :active)');
$stmt->execute(array(
':fullname' => $fullname,
':email' => $email,
':active' => $activasion
));
$id = $db->lastInsertId('memberID');
// Send email
$to = $_POST['email'];
$subject = "Verify Your Account";
$body = "<p>Thank you for registering on the demo site.</p>
<p>Hello ".$fullname.", Please click this link to activate your account: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>";
$mail = new Mail();
$mail->setFrom(SITEEMAIL);
$mail->addAddress($to);
$mail->subject($subject);
$mail->body($body);
$mail->send();
// Redirect to index page
header('Location: register.php?action=joined');
exit;
// Else catch the exception and show the error.
}
catch(PDOException $e)
{
$error[] = $e->getMessage();
}
}
?>
register.php and ajax validations
<script type="text/javascript">
$(document).ready(function() {
$("#fullname").keyup(function(event) {
event.preventDefault();
var fullname = $(this).val().trim();
if(fullname.length >= 1) {
$.ajax({
url: 'registercontrol.php',
type: 'POST',
data: {fullname:fullname},
success: function(response) {
// Show response
$("#vfullname").html(response);
}
});
} else {
$("#vfullname").html("");
}
});
$('#submit').click(function(event) {
event.preventDefault();
var formData = $('#register-form').serialize();
console.log(formData);
$.ajax({
url: 'registercontrol.php',
method: 'post',
data: formData + '&submit=register'
}).done(function(result) {
$('.hidden').show();
$('#result').html(result);
})
});
});
</script>
<?php
// If action is joined show sucesss
if(isset($_GET['action']) && $_GET['action'] == 'joined')
{
echo '<div>
<p>Registration is successful, please check your email to activate your account.</p>
</div>';
}
else
{ ?>
<div>
<h1>Create an Account!</h1>
</div>
<form id="register-form" role="form" method="post"
action="registercontrol.php" autocomplete="off">
<input type="text" name="fullname" id="fullname" placeholder="Your name" value="" required>
<div id="vfullname"></div>
<input type="email" name="email" id="email" placeholder="Your Email" value="" required>
<input id="submit" type="submit" name="submit" value="Create Account">
<p class="hidden">Please check everything.</p>
<div id="result"></div>
</form>
<?php } ?>
Thank you.
Check the done block and perform your redirect with JavaScript:
$('#submit').click(function(event){
event.preventDefault();
var formData = $('#register-form').serialize();
console.log(formData);
$.ajax({
url: 'registercontrol.php',
method: 'post',
data: formData + '&submit=register'
}).done(function(result){
var url_to_redirect = "register.php?action=joined";
window.location.href = url_to_redirect;
})
});
Brief
I am now stuck at a part of AJAX, as I do now know how to extract the data out from the AJAX part and put into the PHP variables, so that I could access it and use it later. It also does not redirect me to another page ("Map.php").
I tried looking online for the answers, but to no avail. Can anyone with experience please help. Also, I am not sure if my method of doing is correct, please let me know where I have done wrong.
In details
I want to do a "Login.php", which will use a form to take the email and password from the user. There will be a "Login" button on the form which will trigger a javascript for the purpose of validation.
Upon validation, I will use AJAX to call another php file called "Auth.php", which will have make a connection with a MySQL database, to search for that particular user verify the user.
The "Auth.php" will then return a json data of the user's particulars, which I intend to use in "Login.php" page, and to start a session with the $_SESSION[] variable of php. I also want the page to redirect the user to another page ("Map.php") upon successful login.
Below are parts of my codes in the "Login.php" and "Auth.php".
Login.php
<form name="myForm" action="Map.php" method="post" onsubmit="return validateForm()">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="email" type="email" autofocus value="<?php echo isset($_POST["email"])? $_POST["email"]: ""; ?>">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="<?php echo isset($_POST["password"])? $_POST["password"]: ""; ?>">
</div>
<input type="submit" value="Login" class="btn btn-lg btn-success btn-block"/>
</fieldset>
</form>
<script>
function validateForm() {
//event.preventDefault();
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email == null || email == "") {
alert("Email must be filled.");
return false;
}
if (password == null || password == "") {
alert("Password must be filled.");
return false;
}
if(re.test(email)) {
var data = {
"email": email,
"password": password
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "GET",
dataType: "json",
url: "auth.php",
data: data,
success: function(data) {
alert("You have successfully logged in!");
// TODO store user details in session
return true; // return true to form, so will proceed to "Map.php"
}
});
return false;
}
else {
alert("You have entered an invalid email address!");
return false;
}
return false;
}
</script>
Auth.php
$connection = mysqli_connect("localhost", "root", "", "bluesky");
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}
$valid=true;
if (isset($_GET['email']) && isset($_GET['password'])) {
$email = addslashes($_GET['email']);
$password = addslashes($_GET['password']);
} else {
$valid = false;
$arr=array('success'=>0,'message'=>"No username or password!");
echo json_encode($arr);
}
if($valid == true){
$query = "SELECT * FROM user WHERE email='$email' and password='$password'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Login failed");
echo json_encode($arr);
}
}
// close the connection that was established with MySQL for the SQL Query
mysqli_close($connection);
Your ajax call should be like this:
data = $(this).serialize() + "&" + $.param(data)
$.post('auth.php', data, function(response){
console.log(response);
});
you must use post method because you are getting password and email so its not a good practice. And for validation there is many jQuery plugins.
I have made a simple login form which I am trying to validate through AJAX call. It works successfully. But problem is when I enter correct email or password it refreshes the whole page instead of showing JSON success-error to be shown in div and same for the wrong email/password. Any suggestions please!!
Code
<script>
$(document).ready(function() {
$('#login_submit').click(function(){
var email = $("#email").val(),
password = $("#password").val();
var proceed = true;
if(proceed){
post_data= { 'Email': email, 'Password': password};
$.post('login_index.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output=$('.alert-error').html(response.text);
}else{
output=$('.alert-success').html(response.text);
}
$("#error").hide().html(output).slideDown();
}, 'json');
}
});
});
</script>
<div class="alert-error"></div>
<div class="alert-success"></div>
<div class="login">
<form method="post" action="">
<input type="email" name="email" id="email" placeholder="email" >
<input type="password" name="password" id="password" placeholder="password">
<input type="submit" name="login_submit" id="login_submit" value="login">
</form>
</div>
Php
<?php
include "db/db.php";
session_start();
if($_POST){
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(isset($_POST['Email']) && isset($_POST['Password']))
{
$email=filter_var($_POST["Email"], FILTER_SANITIZE_STRING);
$pwd=filter_var($_POST["Password"], FILTER_SANITIZE_STRING);
$query=mysqli_query($con,"select * from customers where email='$email' and password='$pwd'");
$count=mysqli_num_rows($query);
$row=mysqli_fetch_array($query,MYSQLI_ASSOC);
if($row)
{
$_SESSION['login_email']=$row['email'];
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$email .' You are successfully login'));
die($output);
}
else{
$output = json_encode(array('type'=>'error', 'text' => 'Could not login! Please check your email password.'));
die($output);
}
}
}
Prevent the default action of form or submit button using e.preventDefault() or else it will post the form and page refresh happens.
$('#login_submit').click(function(e){
e.preventDefault(); //e is the event captured here
//rest of the code
});
You can directly use return false, which will prevent default action and also propagation event.
$('#login_submit').on('click',function(){
//Complete code here
return false;
});
I am developing a website on Codeigniter Framework i am facing an issue while making forgot password feature.
When i submit my email address it sends an email to that address and that email has a link that has a token in it. eg:
http://www.myegsite.com/user/forgotyourpassword/2991c14654e1ed41aab1565dcf815b0f
On click that link, if that token is not expired then, website asks for your new password and confirm password.
The issue is : When i provide new password and confirm password and click submit button it gives me following error:
An Error Was Encountered
The action you have requested is not allowed.
After reloading that same link, the page i get works absolutely fine, it updates my password again.
What could be the reason that link doesn't work first time?
Controller:
public function forgotyourpassword($token)
{
if($this->session->userdata('user_data') != NULL)
{
redirect(base_url() . 'User');
}else
{
//check if token exist in table or not , if not exist return false;
$this->load->model("data_access/extradataaccess","ExtraDataAccess");
$dbToken =$this->ExtraDataAccess->getToken($token);
if($dbToken == FALSE)
{
$this->session->set_flashdata("invalid_token",'This token is invalid!');
redirect(base_url() . 'welcome/forgotPassword');
}
else
{
//check if current date is smaller than expiry data , it means token is still valid return true;
if($this->ExtraDataAccess->GetTokenInfo($token) == FALSE)
{
//set flash data session for token expired
redirect(base_url() . 'welcome/forgotPassword');
//if token is expired return false
} //if ($currDate <= $expiryDate)
else
{
// load form libraries
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confpassword', 'Password Confirmation', 'required|min_length[6]|max_length[20]|matches[password]');
if($this->form_validation->run() == FALSE)
{
$this->data['page_name'] = "Renew Password";
$this->data['form_url'] = base_url()."user/forgotyourpassword/";
$this->data['token'] = "$token";
$this->load->view("welcome/renewpassword_view",$this->data);
}
else
{
$tokenEmail = $this->ExtraDataAccess->GetTokenInfo($token)['email'];
$hashPassword = md5($this->input->post('password'));
//updating password into the database
$updateData = array (
'password' => $hashPassword
);
$this->db->where('email',$tokenEmail);
$this->db->update('users',$updateData);
}
}//else
}
}//if($this->session->userdata('user_data') != NULL)
}//Forgotyourpassword()
View:
<?php echo form_open("$form_url"."$token"); ?>
<div class="form-group">
<label for="inputpass">Password</label>
<input type="password" name="password" class="form-control" id="inputpass" value="" php echo placeholder="new password"/>
</div>
<?php if(form_error('password')!=NULL){
echo "<div id='fielderror'>";
echo form_error('password');
echo "</div>";
}?>
<div class="form-group">
<label for="inputpassconf">Confirm Password</label>
<input type="password" name="confpassword" class="form-control" id="inputpassconf" value="" placeholder="confirm password"/>
</div>
<?php if(form_error('confpassword')!=NULL){
echo "<div id='fielderror'>";
echo form_error('confpassword');
echo "</div>";
}?>
<h5><input type="submit" value="Reset Password" class="btn btn-info active"/></h5>
<?php echo form_close();?>
So i am making a registration page on my website. At the moment it is more just a test then anything. I have it working more or less and when a user attempts to sign up it works just fine HOWEVER there is no change on the page. I have created a Confirmation page but no matter what i try i can't seem to get the button to redirect as well.
<form name="register" method="post" action="register.php">
Username:<input name="user" type="text" id="user">
<br>
Password:<input name="pass" type="password" id="pass">
<br>
Repeat Password:<input name="rpass" type="password" id="rpass">
<br>
<input type="submit" name="submit" value="Register">
</form>
From what i can tell in the last few hours of research the reason onclick and wrapping the button in a link does not work is because the type="submit" instead of "button". Is there any way do make this button redirect? If not with HTML perhaps with a JS or PHP ?
<?php
session_start(); //Must Start a session.
require "config.php"; //Connection Script, include in every file!
//Check to see if the user is logged in.
//'isset' check to see if a variables has been 'set'
if(isset($_SESSION['username'])){
header("location: members.php");
}
//Check to see if the user click the button
if(isset($_POST['submit']))
{
//Variables from the table
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
//Prevent MySQL Injections
$user = stripslashes($user);
$pass = stripslashes($pass);
$rpass = stripslashes($rpass);
$user = mysqli_real_escape_string($con, $user);
$pass = mysqli_real_escape_string($con, $pass);
$rpass = mysqli_real_escape_string($con, $rpass);
//Check to see if the user left any space empty!
if($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill in all the information!";
}
else
{
//Check too see if the user's Passwords Matches!
if($pass != $rpass)
{
echo "Passwords do not match! Try Again";
}
//CHECK TO SEE IF THE USERNAME IS TAKEN, IF NOT THEN ADD USERNAME AND PASSWORD INTO THE DB
else
{
//Query the DB
$query = mysqli_query($con,"SELECT * FROM members WHERE username = '$user'") or die("Can not query the TABLE!");
//Count the number of rows. If a row exist, then the username exist!
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "Sorry, but the username is already taken! Try again.";
}
//ADD THE USERNAME TO THE DB
else
{
$add = mysqli_query($con,"INSERT INTO members (id, username, password) VALUES (null, '$user' , '$pass') ") or die("Can't Insert! ");
}
}
}
}
?>
As I commented, simply do
else
{
$add = mysqli_query($con,"INSERT INTO members (id, username, password) VALUES (null, '$user' , '$pass') ") or die("Can't Insert! ");
header("location: thankyou.html");
}