validation username by html onblur in codeigniter - javascript

I have a signup page in Codeigniter. I want to check the username exists or not exists, when they type it and exit from its input object (onblur event).
It mean I want to check if the username exists or not when users type it and also when losing focus on the input field?
How I can check it?
I share part of my codes at bellow:
My model (its return True or False):
public function Check_UserName_Validate(){
$CMD = "call UserName_Validate($this->input->post('edtUserName'));";
$query = $this->db->query($CMD);
if (mysqli_more_results($this->db->conn_id))
mysqli_next_result($this->db->conn_id);
return $query->row();
}
My View:
<div>
First Name : <input type="text" id="edtFirstName" class="MyInputs">
<br>
Last Name : <input type="text" id="edtLastName" class="MyInputs">
<br>
Username : <input type="text" id="edtUserName" class="MyInputs">
<br>
Password : <input type="password" id="edtPassword" class="MyInputs">
</div>
My Controller:
public function Signup($Flag = 0){
...
$data["ErrorMSG"] = "";
$data["ErrorKind"] = 0;
$this->form_validation->set_rules("edtFirstName", $data["FirstName_Caption"], "trim|required");
$this->form_validation->set_rules("edtLastName", $data["LastName_Caption"], "trim|required");
$this->form_validation->set_rules("edtUserName", $data["Username_Caption"], "trim|required");
$this->form_validation->set_rules("edtPassword", $data["Password_Caption"], "trim|required");
if ($Flag == 1){
if ($this->form_validation->run() == FALSE) {
$data["ErrorMSG"] = validation_errors();
$data["ErrorKind"] = 4;
$this->load->view("Signup", $data);
}
else{
/* Insert user information to database */
}
}
else{
$this->load->view("Signup", $data);
}
}
Please guide me.
Thanks

You could have an AJAX function checking on the edtUserName field changes.
$(document).ready(function(){
var $username_field = $('#edtUserName');
$username_field.on('keyup', function(){
check_username($(this).val());
});
$username_field.on('blur', function(){
check_username($(this).val());
});
});
function check_username(value)
{
$.post('site/username_exits', {edtUserName : value}, function(response) {
if (response.exists) {
// perform what is necessary when the username exists
}
}, "json");
}
In your controller, you would add:
public function username_exits()
{
if($this->input->is_ajax_request())
{
// load model first
$this->load->model(<MODEL-NAME>);
$exists = $this-><MODEL-NAME>->Check_UserName_Validate($this->input->post('edtUserName'));
echo json_encode(array('exists' => $exists));
}
else
{
show_404();
}
}
Then you should change a little thing in your model function. Remove $this->input->post from it and pass the username as a parameter. This way you'll leave the job of collecting data to the controller.
public function Check_UserName_Validate($username){
$CMD = "call UserName_Validate(?);";
$query = $this->db->query($CMD, $username);
if (mysqli_more_results($this->db->conn_id))
mysqli_next_result($this->db->conn_id);
return $query->row();
}

For check duplicate result you can use simple form_validation is_unique method like that -
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
where is_unique is a method and users is a table name and email is column name in database table, using that you can check uniqueness.
Form Validation | CodeIgniter 3.1.7 documentation

Related

How to disable form submit button if the username already exits in database ? (by js, ajax, php(laravel))

I am new js learner, and I am trying to build a form. in the form I want to check if the input username is already taken or exists and I have done this by laravel controller and lil JS code but I want to HIDE the submit button if the input username is already exists in the database. so how do I do this? please anybody
This is my JS code
<script type="">
$function get_user_name(id, result) {
var id = $(id).val();
$.get("<?php echo e(url('home/get_user_name')) ?>/" + id,
function (data) {
$(result).html(data);
});
}
</script>
Controller =>
**and
controller =**
public function get_user_name()
{
$username = request()->segment(3);
$user = DB::table('users')
->select('username')
->where('username', $username)
->count();
$nam = "username already taken";
if ($user >0) {
return $nam;
}else{
}
}
html form =>
<span id="username_rs" style="color: green; font-weight: bold"></span>//showing the message here,
<input id="username" name="username"
onchange="checkem('#username', '#username_rs')" >
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
route =>
Route::get('/home/get_user_name/{username}', 'HomeController#get_user_name')->name('checkun');
And url look like =>
http://localhost/home/get_user_name/{input username}
My code is showing if the username is taken or not, but I want to hide the submit button if the username is taken or exists in the database.
You can return like this:
**and
controller =**
public function get_user_name()
{
$username = request()->segment(3);
$user = DB::table('users')
->select('username')
->where('username', $username)
->count();
if ($user >0) {
return Response::json(array("found"=>"yes", "message"=>"Username is already taken"));
}else{
return Response::json(array("found"=>"no", "message"=>"Something happens wrong"));
}
}
Your Script code looks like:
$function get_user_name(id, result) {
var id = $(id).val();
$.get("<?php echo e(url('home/get_user_name')) ?>/" + id,
function (data) {
if (data.found == 'yes)
{
$("#submit_btn").css("display","none")
}
});
}
HTML code looks like:
<span id="username_rs" style="color: green; font-weight: bold"></span>//showing the message here,
<input id="username" name="username"
onchange="checkem('#username', '#username_rs')" >
<button type="submit" id="submit_btn" class="btn btn-primary">
{{ __('Register') }}
</button>
I would do it like this:
function get_user_name(id, result) {
var id = $(id).val();
$.get("<?php echo e(url('home/get_user_name')) ?>/" + id,
function (data) {
//check if we get the message: username already taken
if(data) {
$(result).html(data);
$('input[type=submit]', this).attr('disabled', 'disabled'); //disable button
$('form').bind('submit',function(e){e.preventDefault();}); //disable form
} else {
$('input[type=submit]', this).removeAttr('disabled', 'disabled'); //enable button
$('form').unbind('submit'); //enable form
}
});
}

How to show an error if an input field is empty in a form using ajax

Please help. I've been stuck on the same problem for about two weeks now. So I downloaded the advanced login master script from Github and customized it a bit.
Advanced login script
Everything was going fine until I created a Post class and tried adding an ajax form to the "views/logged_in.php" file. The form validation error messages stopped showing up correctly. I'm trying to check if the input field is empty for the form before submitting the form via Ajax. I'm not used to the way this script has been set up. The index file seems to call the classes. But when I try to add ajax it throws me off completely.
Can somebody please show me the proper way to add a simple ajax form to this script within the "views/Logged in.php" file while displaying an error message if the input field is empty?
P.S. I want to display a PHP error, not a Javascript error. In my Post class I have an array for errors and messages.
Here is my javascript ajax code.
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$("form.ajax")[0].reset();
console.log(response);
}
});
return false;
});
website.com/views/logged_in.php
<form action="<?php echo BASE_URL; ?>contact.php"` method="post" class="ajax">
<div class="new_post_header">
<div class="new_post_avatar"><img src="img/profile_pic_1.png" style="width:40px; height:40px;" /></div>
<textarea name="post_text" id="message" class="new_post_textarea" placeholder="Give a tip"></textarea>
</div><!--.new_post_header-->
<div id="new_post_options">
<div class="icon-camera post_options_icon"></div>
<div class="icon-camcorder post_options_icon"></div>
<div class="icon-tag post_options_icon"></div>
<button name="submit" type="submit" class="post_post_button">Post</button>
<a class="privacy_post_option" id="post_privacy_toggle">
<div class="icon-earth-grid privacy_option_icon"></div>
Public
<div class="icon-more-arrow privacy_option_arrow"></div>
</a>
</div><!--#new_post_options-->
</form><!--.ajax-->
website.com/classes/Post.php class
<?php
class Post
{
/**
* #var object $db_connection The database connection
*/
private $db_connection = null;
/**
* #var string $logged_in_user_id the poster's id variable
*/
public $logged_in_user_id = null;
/**
* #var string $post_text The post text variable
*/
public $post_text = "";
/**
* #var array collection of error messages
*/
public $errors = array();
/**
* #var array collection of success / neutral messages
*/
public $messages = array();
/**
* Checks if database connection is opened and open it if not
*/
private function databaseConnection()
{
// connection already opened
if ($this->db_connection != null) {
return true;
} else {
// create a database connection, using the constants from config/config.php
try {
// Generate a database connection, using the PDO connector
// #see http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
// Also important: We include the charset, as leaving it out seems to be a security issue:
// #see http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Connecting_to_MySQL says:
// "Adding the charset to the DSN is very important for security reasons,
// most examples you'll see around leave it out. MAKE SURE TO INCLUDE THE CHARSET!"
$this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
return true;
// If an error is catched, database connection failed
} catch (PDOException $e) {
$this->errors[] = MESSAGE_DATABASE_ERROR;
return false;
}
}
}
/**
* creates a new post in the databse
*/
public function submitPost($logged_in_user_id, $post_text)
{
// remove extra space on post text
$post_text = trim($post_text);
// if the post text is empty
if (empty($post_text)) {
// show the errors
$this->errors[] = MESSAGE_USERNAME_EMPTY;
} else if ($this->databaseConnection()) {
// write new post data into database
$query_new_post_insert = $this->db_connection->prepare('INSERT INTO posts (poster_id, post_text, post_date) VALUES(:poster_id, :post_text, NOW())');
$query_new_post_insert->bindValue(':poster_id', $logged_in_user_id, PDO::PARAM_INT);
$query_new_post_insert->bindValue(':post_text', $post_text, PDO::PARAM_STR);
$query_new_post_insert->execute();
// id of new post
$post_id = $this->db_connection->lastInsertId();
// return the id of the last post to be added to database
return $post_id;
}
}
/**
* creates a new post in the databse
*/
public function getPost($logged_in_user_id)
{
// remove extra space on post text
$post_text = trim($post_text);
if ($this->databaseConnection()) {
// write new post into database
$query_new_post_insert = $this->db_connection->prepare('INSERT INTO posts (post_text) VALUES(:post_text)');
$query_new_post_insert->bindValue(':post_text', $post_text, PDO::PARAM_STR);
$query_new_post_insert->execute();
// id of new post
$post_id = $this->db_connection->lastInsertId();
// return the id of the new post
return $post_id;
}
}
}
website.com/contact.php
<?php
// start the seesion so that you can access the $_SESSION variable
session_start();
// put the current logged in user's id in a variable
$logged_in_user_id = $_SESSION['user_id'];
// include the config
require_once('config/config.php');
// include the to-be-used language, english by default. feel free to translate your project and include something else
require_once('translations/en.php');
// load the post class
require_once('classes/Post.php');
// create the post object
$post = new Post(
);
if (isset($_POST['post_text'])) {
// put the post text in a variable
$post_text = $_POST['post_text'];
// put the returned id from the submited post into a variable
$post_id = $post->submitPost($logged_in_user_id, $post_text);
}
?>
Hi i have make your submit button as button and onclick i have called ajax function
function test1()
{
var that = $('.ajax'),
url = 'contact.php',
type = 'POST',
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
if(value=='')
{
alert("please enter value of " +name);
}
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
if(response==2)
{
alert("plaese enter text");
or
$('.error').html("plaese enter text");
}
if(response==1)
{
$("form.ajax")[0].reset();
}
console.log(response);
}
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" class="ajax">
<div class="new_post_header">
<div class="new_post_avatar"><img src="img/profile_pic_1.png" style="width:40px; height:40px;" /></div>
<textarea name="post_text" id="message" class="new_post_textarea" placeholder="Give a tip"></textarea>
</div><!--.new_post_header-->
<div id="new_post_options">
<div class="icon-camera post_options_icon"></div>
<div class="icon-camcorder post_options_icon"></div>
<div class="icon-tag post_options_icon"></div>
<button type="button" onclick="return test1();" class="post_post_button">Post</button>
<a class="privacy_post_option" id="post_privacy_toggle">
<div class="icon-earth-grid privacy_option_icon"></div>
Public
<div class="icon-more-arrow privacy_option_arrow"></div>
</a>
</div><!--#new_post_options-->
</form><!--.ajax-->
A very simplified way of doing this would be:
$('form.ajax').on('submit', function() {
var empty = true;
$("form.ajax input").each(function(){ // check each input
var val = $(this).val();
if(!$.trim(val) == ""){ // if the inputs are not empty
empty = false; // allow ajax to be submitted
}
});
if(empty){
alert("Input is empty!"); // alert that an input is empty
} else {
// ajax goes here
}
return false; // prevent form post
});
Note: This procedure also works if the inputs contain JUST white space (no text). I would suggest checking for this on the server-side too, not just the client-side (as this is editable within the (potential) attackers) browser.

jQuery form, exist checking

So i am creating a simple form that checks whether or not the value that the user is inputting exists or not in my DB using jQuery. Everything up until now is working so far however i find myself stuck at this next part.
To easily explain i will just show an example of what i am trying to achieve.
For this example i will be "weeden"
weeden has an ID of 255 in the company table of my database.
If the user types in "weeden" into the client field
To the right of the client field (on the web form), the text "weeden is unavailable" will appear
what i would like to have happen instead is this: "ID 255 is unavailable"
Here is the relevant code.
HTML FORM
<form action="addrecord.php" method="post" autocomplete="off"/>
<div class="form-field">
<label for="client">Client: </label>
<input type="text" name="client" id="client" class="check-exists" data-type="client" placeholder="#">
<span class="check-exists-feedback" data-type="client"></span>
</div>
jQuery Function
$.fn.existsChecker = function(){
return this.each(function(){
var interval;
$(this).on('keyup', function(){
var self = $(this),
selfType = self.data('type'),
selfValue,
feedback = $('.check-exists-feedback[data-type=' + selfType + ']');
if(interval === undefined){
interval = setInterval(function(){
if(selfValue !== self.val()){
selfValue = self.val();
if(selfValue.length >= 1){
$.ajax({
url: 'check.php',
type: 'get',
dataType: 'json',
data: {
type: selfType,
value: selfValue
},
success: function(data){
if(data.exists !== undefined){
if (data.exists === true){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is available');
}
}
},
error: function(){
}
});
}
}
}, 1000);
}
});
});
};
Check.php
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,
array('client')
)
){
switch($type){
case 'client':
$check = $db->prepare("
SELECT COUNT(*) AS count
FROM company
WHERE name = :value
");
break;
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
Any help/suggestions would be greatly appreciated. I consider myself a beginner, this is my first time working on a web project.
Just to clarify ahead of time, there are many other input fields on the same webform such as: email, date, first, last, etc.
I hope my question was clear enough. Thank you
You have to change your Query to something like this:
$check = $db->prepare("
SELECT id, COUNT(*) AS count
FROM company
WHERE name = :value
");
I assume that your primary key field on the company-table is named id.
And finally store the id in the output-Array
$result = $check->fetchObject();
$output['exists'] = $result->count ? true: false;
$output['id'] = $result->id;
Then you can output the id like so:
if (data.exists === true){
feedback.text('ID ' + data.id + ' is unavailable');
}
You can handle everything in query
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,array('client'))){
switch($type){
case 'client':
$check = $db->prepare("
SELECT (CASE WHEN(COUNT(id)>0) THEN id ELSE FALSE END) AS count
FROM company WHERE name = :value ");
break;
}
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
}
In Ajax success
if(data.exists !== undefined){
if (!data.exists){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is already taken.');
}
}

How to check if USERNAME already exists in PHP/MYSQL?

I'm currently configuring my "User Registration" form in PHP.
Trying to create a simple function to check if the username already exists in the database
After doing my research, I have found that there are several ways this can be done.
(a) the best way is probably to use a PHP/AJAX combination, to check right away if the username already exists (in other words, the check is done BEFORE the user clicks the "Submit" button;
(b) the other way is to do a simple SQL-query, which will return an error message, if that particular username already exists in the database. (The only drawback with this method is that : the check is done only AFTER the user clicks the "Submit" button.
I would have preferred Option A, of course. But, I was unsuccessful in my attempts to create a working AJAX/jQuery script.
So, I went with Option B instead.
And, I got it working.
Here is the simply query I used :
if(isset($_POST['submit1'])||isset($_POST['submit1'])) {
$login = $_POST['login'];
$query_login = "SELECT login FROM registration WHERE login='$login';";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "Sorry, that Username is already taken. Please choose another.";
return false; }
else { //proceed with registration
It worked fine. The error was displayed.
The only problem is : the registration form itself disappeared.
I would have liked to display the error on the same page as the registration form, without having to RESET or somehow GO BACK.
I know that the reason for this is something very minor (and kinda stupid on my part :D :D)
Probably something to do with that "return false" thingy at the end of the query.
But, I am not sure.
(a) How can I get the error message displayed on the form-page itself?
(b) Or, better yet, is there a JavaScript Function I can use for this, so that I can simply call the function in the "Submit" button................like so : onSubmit = return function() ??
Thanks
UPDATE: Here is my form code.
form action="myform.php" method="post">
<br>
Choose a username : <input type="text" name="login" value="<?=$login?>"
required>
UPDATE
I was able to find the following jQuery code :
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = 'Checking...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("check_username.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html(username + ' is
Available');
}else{
//show that the username is NOT available
$('#username_availability_result').html(username + ' is not
Available');
}
});
}
I assume that, for my particular example :
(a) the jQuery file cannot be inserted into the actual PHP file (my php file is named : registration.php, which includes both the html and php);
(b) this particular jQuery file includes a "button", which needs to be clicked to check if the username already exists. This is not a bad idea; but, I would rather that this was done automatically, without the need to click on a button (let's face it : there are some users out there who are indeed too clueless to perform this simple check manually). My aim is free the user as much as possible from the need to do such trivial tasks :D
Anyway, my point is : so as to eliminate the need for a button, I would like to include an auto-function which checks once the user types in the username.
According to Google, the following function is what I need :
Replace $(‘#check_username_availability’).click(function(){ … with $(‘#username’).keyup(function(){ …
(c) Isn't there any way to actually insert that JQUERY into "registration.php" ?? Or, should it be a separate file entirely?
The better way would be you bind the ".blur" event on which you may check if the username is valid via ajax. Don't forget to check the username after form submission at before form submission.
Below your input box create a
<span class= "error">Username is already present. </span>
<span class= "success">Username can be assigned. </span>
and just display the message accordingly.
You may use the script as
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {"username",$("input.username").val()},
success : function (data)
{
if(data == "success")
{$(".success").show();$(".error").hide();}
else
{$(".error").show();$(".success").hide();}
},
});
You php code would be something like this :
$query = "SELECT username FROM tab_users WHERE username = '".$_POST['username']."'";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "fail";
return false;
}
else
{
echo "success";
return false;
}
You can disable the submit button and add a span message near the input field.
Check this code:
function checkUsername()
{
var username = document.getElementById('username');
var message = document.getElementById('confirmUsername');
/*This is just to see how it works, remove this lines*/
message.innerHTML = username.value;
document.getElementById("send").disabled = true;
/*********************************************/
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {username: username},
success: function (response) {
if (response==0)
{
message.innerHTML = "Valid Username";
document.getElementById("send").disabled = false;
}
if (response==1)
{
message.innerHTML = "Already Used";
document.getElementById("send").disabled = true;
}
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="uername">Username:</label>
<input type="text" class="form-control" name="username" id="username" onkeyup="checkUsername(); return false;" required/>
<span id="confirmUsername" class="confirmUsername"></span>
<button type="submit" id="send" name="action" value="Send">Send</button>
put this
include([your validating php file]);
and in your form action link to your login form file.
note : your login file have to be php file.

Submitting a form using php, with email check via javascript

First time poster, long time reader, so I'll get right to the point.
I'm working on a project for school and this question kind of goes way beyond the requirements of the project, but it'll look awesome once it's finished. I've got 3 pieces of code that aren't cooperating--a piece of html/php, a piece of php, and javascript.
The ultimate goal of my code is this:
Here's a form, submit your email and IF it's a #trnty.edu address (my school), submit the form.
The problem currently is that the form submits blank data--proof being the many empty lines on my sql server.
I've tested manually setting variables, and it does work (via the emailsubmit.php code), the emailcheck.js code does check for a proper email, but they don't talk to each other properly.
Ya'll mind giving me a hand? I've been at this for about 3 weeks searching this (and other) websites via Google for possible solutions. Many thanks!
(my form code from the homepage)
<div id="signupform">
<form id="signup" action="scripts/emailsubmit.php" method="POST">
<input type="email" name="email" placeholder="school email address" />
<button id="sub">Submit</button>
</form>
My current Javascript -- I'm not sure what or how to fill in the blank...
$(function(){
$('#signup').submit(function()
{
if(validateEmail($('input').val()))
{
return true;
}
else
{
return false;
}
});
function validateEmail(email)
{
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email))
{
if (email.indexOf('#trnty.edu', email.length - '#trnty.edu'.length) !== -1)
{
//alert('Submission was successful.'); //if true, submit form -- see video
return true;
}
else
{
alert('Email must be a Trinity email address (your.name#trnty.edu).');
return false;
}
}
else {alert('Not a valid e-mail address.');}
}
});
Myphp code.
<?php
$dbhost = 'localhost';
$dbuser = 'service';
$dbpass = '!##$%';
$db = 'tbv_main';
$con = mysqli_connect($dbhost,$dbuser,$dbpass,$db);
//$email = $_POST['email'];
//$email = 'itworked#kickass.net';
$sql = "INSERT INTO stage1 (email, counter) VALUES ('$email', NULL)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Email: $email , 1 record added";
?>
your jQuery .submit() is cancelling the default form submission with return false; but there's no ajax to send the data to the server, so what you actually want to do is return false after the negative alerts, and return true at when your regexp passes, then check it in your submit function.
$('#signup').submit(function() {
if(validateEmail($('input').val())){
return true;
}else{
return false;
}
});
Then in your validate function.
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#trnty.edu', email.length - '#trnty.edu'.length) !== -1)
{
//alert('Submission was successful.'); //if true, submit form -- see video
return true;
}
else {
alert('Email must be a Trinity email address (your.name#trnty.edu).');
return false;
}
} else {
alert('Not a valid e-mail address.');
return false;
}
return false;
In doing so, your form will submit when the regexp is properly validated and the page will refresh causing your php code to fire.

Categories