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.
Related
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
Question as stated above. I am using older browsers (IE8 and FF8) due to corporate policy. I can't fix this but my research says this isn't the issue...(yeah right;)
I'm using PHP 5.5.12 on Apache 2.4.9 with a MySQL (5.6.17) back end. The site is a CMS that has grown organically over several years.
I have a user admin page that adds, updates, and deletes accounts. However, no matter what I have done the form submits. The worst example is if the admin chooses to delete an account and when asked 'Do you really wish to DELETE...?' and cancels, it is still deleted! I've copied my JavaScript and an excerpt from the PHP/HTML below.
I have tried a few changes to my JavaScript like returning after setting the window.event.returnValue but I've always gotten the same results. I've been reading for several days now and keep coming up blank! I've tried onSubmit instead of onClick but it really doesn't suit the site, besides it didn't work either.
I'm beginning to think the age of the browsers is the issue. I run this with Safari on my home development box fine. Any help would be appreciated.
JavaScript
<script language="JavaScript">
function frmVerify(check, loginid, login) {
if (check == 'add') {
Uname=add_user.login_name.value;
Pass1=add_user.password.value;
Pass2=add_user.password2.value;
if(Uname=='') {
alert('A user name must be assigned to an account.');
window.event.returnValue=false;
}
if(Uname == login) {
alert('You cannot create an account with your own username (' + login + ')');
window.event.returnValue=false;
}
if(Pass1 != Pass2) {
alert('Entered passwords are not the same! Make sure the password and verification fields match.');
window.event.returnValue=false;
}
if(Pass == '') {
alert('Assigning a password is required when creating an account!');
window.even.returnValue=false;
}
} else if(check == 'update') {
Uname=eval('edU_'+loginid+'.login_name.value');
Pass1=eval('edU_'+loginid+'.password.value');
Pass2=eval('edU_'+loginid+'.password2.value');
if(Uname == '') {
alert('A user name must be assigned to an account.');
window.event.returnValue=false;
}
if(Pass1 != Pass2) {
alert('Entered passwords do not match! Make sure the passowrd and verification fields match.');
window.event.returnValue=false;
}
} else if(check == 'del') {
Uname=eval('edU_'+loginid+'.login_name.value');
if(Uname == '') {
request = 'Do you really wish to DELETE this user account?';
} else {
request = 'Do you really wish to DELETE user: ' + Uname + '?';
}
var answer = confirm(request);
if(answer) {
window.event.returnValue=true;
} else {
window.event.returnValu=false;
}
}
}
</script>
In the PHP/HTML I have
echo "<form name=\"delU_$login_id\" id=\"delU_$login_id\" mehtod=\"POST\">";
echo "<input type=\"image\" src=\"./images/delete.png\" value=\"Delete\" onClick=\"return frmVerify('del', '$login_id', '$username');\">";
echo "</form>";
window.event.returnValue (which you don't always spell correctly anyway) is non-standard and shouldn't be used.
You're using 1990s style intrinsic event attributes instead of addEventListener, so just:
return false;
If you were using addEventListener then you would:
event_object.preventDefault();
where event_object is the first argument to your event handler function.
I have the following sequence on a form page, first it runs through the captcha then it validates the email address and then asks if you are sure you want to unsubscribe.
Everything works perfectly except that clicking "Cancel" still submits the form. I can't use "onclick" in the submit button because it will bypass the captcha code. In my "if the email is true 'else'" statement I've tried both "return" and "return:false" but neither of them stop the form submission.
Thanks for your help.
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' name="unsubscribe" method='post' onsubmit="return checkForm(this);"">
function checkForm(form) {
var frm = document.unsubscribe;
if(!form.captcha.value.match(/^\d{5}$/)) {
alert('Please enter the CAPTCHA digits in the box provided');
form.captcha.focus();
return false;
}
if (validEmail(frm.Email.value) != true) {
alert("Please enter a valid email address");
frm.Email.focus();
return false;
}
if (validEmail(frm.Email.value) == true) {
confirm('Are you sure you want to unsubscribe?');
return true;
}
else {
return false;
}
}
function validEmail(email){
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
status = false;
}
else {
status = true;
}
return status;
}
confirm returns a boolean - true if the user clicked "Ok", false if they clicked "Cancel", so simply return the result of the confirm call:
if (validEmail(frm.Email.value) == true) {
return confirm('Are you sure you want to unsubscribe?');
}
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.
I've looked around different questions relating this topic, but none have what I need. I seems simple, but it's still not working. Logically I thought it would work. I have a login form, where I query a select for the user and the password, after that I check if the user and the pw are empty, if not I check if it's in the data base. If it's in the data base redirect somewhere else. Here's the thing, when I load the page, I don't see the txtBox or anything. If I delete the php chunk, everything works fine. Any advice or help would be appreciated.
What I wrote:
<html>
<head>
<link rel = "stylesheet" href = "longInStyle.css">
<script>
function fieldValidation()
{
if( document.getElementById("username").value == "" || document.getElementById("username").value == " " )
{
alert("The username field is empty. Please, enter a username");
document.getElementById('username').focus();
return false;
}
else if(document.getElementById("password").value == "" || document.getElementById("password").value == " " )
{
alert("The password field is empty. Please, enter a password");
document.getElementById('password').focus();
return false;
}
else
{
<?php
include 'config.php';
$usr = $_POST["username"];
$pass = $_POST["password"];
$usrCount = 0;
$passCount = 0;
$SQLUsr = " SELECT USERNAME FROM Users WHERE USERNAME = '$usr' ";
$result = mysql_query($SQLUsr);
$SQLPass = " SELECT PASSWORD FROM Users WHERE PASSWORD = '$pass' ";
$result2 = mysql_query($SQLPass);
$usrCount = mysql_num_rows($result);
$passCount = mysql_num_rows($result2);
if($result == 1)
{
$SQLLvl = " SELECT USERLEVEL FROM Users WHERE USERNAME = '$usr' ";
$result3 = mysql_query($SQLLvl);
if($result2 == 1)
{
if($result3 == "Super")
{
header("location:superUserMain.html");
}
else
{
header("location:editMain.html");
}
mysql_close($db_handle);
}
else
{
<script>
alert("The wrong password.");
document.getElementById('password').focus();
</script>
}
}
else
{
<script>
alert("The wrong username.");
document.getElementById('username').focus();
</script>
}
?>
return true;
}
}
</script>
</head>
<body>
<form method = "post" onsubmit = " return fieldValidation()">
<div>
<div>
Username
</div>
<input type = "text" name = "username" id = "username">
</div>
<div>
<div>
Password
</div>
<input type = "password" name = "password" id = "password">
</div>
<div>
<input type="submit" id = "logIngBtn" name = "logInBtn" value = "Login">
</div>
</form>
</body>
</html>
I saved it as a php file.
config.php has the data base credentials. Username, password and everything else to access it.
To expand on John Condes comment:
You're using JavaScript to control whether PHP code will be executed. This isn't possible (at least not in the way you're trying to do it). PHP code runs on the server, before anything is sent to the client (the users browser). JavaScript (in your context, at least) only runs in the client (the users browser). By the time your JS decides whether the PHP should run, it's too late. The browser has no understanding of the PHP code you're giving it.
I'd suggest starting with a good tutorial on how to build an AJAX login form with PHP and MySQL.
Ignore the haters man...
To help you out though it might be a idea to do what John Conde and mchandleraz said. But to be fair if you are new to this then I think you are doing really well... I still use procedural code as I'm still learning and none of my code is live.
Jay Blanchard is right though mysql_ functions and procedural code is being deprecated and can pose a massive security risk on a live site as someone could potentailly hack your database and steal or your customers information for example. BTW don't take comments on here to heart, programmers tend to be straight talking people by nature.. so don't be surprised if you do something wrong to get slammed for it!
In regards to your question though there are a ton of youtube videos that you can follow on this kind of stuff... failing that buy a book.
Hope you resolve your issue.
Happy coding! :)