I am using this function to check username availability when registering, and if the username exist, the submit button is disabled. I'm using a php script to check if the username exists in the database. The code works perfectly in my local server, but when hosted on a Godaddy server, I get the below error when I submit or when I try to navigate to another page:
After the empty response, I can't access my website for about a minute and then it's fine.
I tried a lot of things like calling jquery.js file before all other js files, but nothing works for me.
I am not very good with jQuery and javascript. Thank you for your suggestions.
ere is the script and the HTML form :
function check_availability_username() {
var min_chars = 4;
var max_chars = 30;
var re = /^\w+$/;
var characters_error1 = 'Minimum amount of chars is 4';
var characters_error2 = 'Maximum amount of chars is 30';
var characters_error3 = 'Chars can be only letters, numbers and underscores!';
var checking_html = 'Checking...';
var username = $('#username').val();
$.post("check_username.php", {
username: username
},
function(result) {
if (result == 1) {
if ($('#username').val().length < min_chars) {
$('#username_availability_result').html(characters_error1);
$('input[name=submit]').attr('disabled', true);
} else if ($('#username').val().length > max_chars) {
$('#username_availability_result').html(characters_error2);
$('input[name=submit]').attr('disabled', true);
} else if (!re.test($('#username').val())) {
$('#username_availability_result').html(characters_error3);
$('input[name=submit]').attr('disabled', true);
} else {
$('#username_availability_result').html(username + ' is Available');
$('input[name=submit]').attr('disabled', false);
}
} else {
$('#username_availability_result').html(username + ' is not Available');
$('input[name=submit]').attr('disabled', true);
}
});
if (event.which == 13 || event.keyCode == 13) {
$.post("check_username.php", {
username: username
},
function(result) {
if (result == 0) {
$('#username_availability_result').html(username + ' is not Available');
$('input[name=submit]').attr('disabled', true);
}
});
}
$('#submit').click(function() {
$.post("check_username.php", {
username: username
},
function(result) {
if (result == 0) {
$('#username_availability_result').html(username + ' is not Available');
$('input[name=submit]').attr('disabled', true);
}
});
});
}
<form id="login-id" action="suscribe-form.php" method="POST" onkeyup="return check_availability_username();">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control button-or-space" name="username" id="username" value="" minlength="4" maxlength="25" required pattern="\w+">
<input type='hidden' id='check_username_availability' value='Check Availability'> <span id='username_availability_result' name='username_availability_result'></span>
</div>
<div class="form-group">
<label for="password1">Password</label>
<input type="password" class="form-control button-or-space" name="password1" id="password1" value="" minlength="8" maxlength="60" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" onchange="form.password2.pattern = this.value;">
</div>
<div class="form-group">
<label for="password2">Confirm password</label>
<input type="password" class="form-control button-or-space" name="password2" value="" minlength="8" maxlength="60" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}">
</div>
<div class="form-group pull-right">
<input type="submit" name="submit" id="submit" value="Register" class="btn btn-success button-or-space">
</div>
</form>
And here is the php script :
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('DB');
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query('select username from user where username = "'.$username.
'"');
if (mysql_num_rows($result) > 0) {
echo 0;
} else {
echo 1;
}
?>
I finally found the solution. The problem was not from the jQuery or the php script, i only changed the way i call the function in the form from : onkeyup to onchange, and it is now working like a charm. I hope this tip avoid to others losing hours of time like it did to me. Thank's guys for your suggestions.
If you are getting 500 error that there is problem with the database connection.
check for the included files and connection variables used for database connection.
Hope that will work.
Related
I'm sending data via an HTML form to a PHP file for it to be inserted into a DB with SQL script,
The same form is validated with JavaScript functions.
Each of the two works as expected separately,
but when used together - <form method="POST" action="myPHPFile.php" onsubmit="validationFunc(event)"> -
only the validation function works, and the page doesn't get redirected to the PHP file.
When removing the JS (leaving only <form method="POST" action="myPHPFile.php">) - the data from the form is submitted properly and the page is redirected to the PHP file as expected.
I need to have some JS function to stop if the input is invalid,
and another to continue and send the input data to the PHP file if it's valid.
Example code:
function isInputChars(evt) {
let ch = String.fromCharCode(evt.which);
if (!(/[a-z,A-Z,-]/.test(ch))) {
alert("Please only enter only characters")
evt.preventDefault();
}
}
function validateForm(event) {
event.preventDefault();
var validateFormInputs = [];
var inputLength;
StringInput = document.getElementById("city");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("City: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
StringInput = document.getElementById("street");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("Street: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
var x;
for (var i = 0; i < 2; i++) {
if (validateFormInputs[i] === false) {
x = false;
break;
} else {
x = true;
}
}
if (x == true) {
console.log("Data is sent to DB")
someFunctionToContinueSendingTheData();
} else {
console.log("Data is INVALID")
someFunctionToStop();
}
}
<form name="myForm" method="POST" action="sendItem.php" onsubmit="validateForm(event)">
<input id="city" name="city" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input id="street" name="street" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input type="submit" class="btn btn-primary btn-lg" value="Publish">
</form>
I'd be happy for some help with:
How to redirect the input data to the PHP file (without removing the JS validation)
How to implement the JS functions to send the data to the PHP/cancel.
Thank you!
Instead of the button being a submit button just have it be a regular button that calls your javascript function. Then, do all of your validation in the function... at the end, you can have a conditional statement which checks if all conditions are met. If they are, then submit the form. (Assign an id to your form)
Check out this pseudo-code
let me know if this works or you need further instruction
function validateForm(){
... conditional logic ...
if(all conditions met){
document.getElementById('form-id').submit();
}
}
It simple you need to use AJAX to Send a Request To your PHP Server
i will show you a simple example
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object.
you can use POST or GET
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server).
Sending a large amount of data to the server (POST has no size limitations).
Sending user input (which can contain unknown characters), POST is more robust and secure than GET.
<script type="text/javascript">
function myFunction() {
var name = document.getElementById("name").value; // get the name
var email = document.getElementById("email").value; // get the mail
var xhttp = new XMLHttpRequest();
var url = 'test.php'; // your php file
xhttp.open('POST', url, true); // method =POST
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// send data
var params="name="+name+"&email="+email;
xhttp.onreadystatechange = function() {
//Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);
}
}
xhttp.send(params);
}
</script>
<form name="myform" method="POST">
<input type="text" name="name" id="name">
<input type="mail" name="email" id="email">
<input class="btn btn-success" type="button" name="conf" value="OK" onclick="myFunction()">
<input class="btn btn-danger" type="reset" name="cancel" value="cancel">
</form>
You need some changes in your code:
First: you can set validation function on the submit input.
<input type="submit" class="btn btn-primary btn-lg" value="Publish" onclick = "return validateForm();">
Second: you must return true or false at validation function.
if (x == true) {
console.log("Data is sent to DB");
return true; //input data is valid!
someFunctionToContinueSendingTheDate();
} else {
console.log("Data is INVALID")
someFunctionToStop();
return false; //input data is invalid!
}
Finally: here you are:
HTML:
<form name="myForm" method="POST" action="sendItem.php">
<input id="city" name="city" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input id="street" name="street" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input type="submit" class="btn btn-primary btn-lg" value="Publish" onclick="return validateForm();"></form>
JS:
<script>
function isInputChars(evt) {
let ch = String.fromCharCode(evt.which);
if (!(/[a-z,A-Z,-]/.test(ch))) {
alert("Please only enter only characters")
evt.preventDefault();
}
}
function validateForm() {
var validateFormInputs = [];
var inputLength;
StringInput = document.getElementById("city");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("City: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
StringInput = document.getElementById("street");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("Street: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
var x;
for (var i = 0; i < 2; i++) {
if (validateFormInputs[i] === false) {
x = false;
break;
} else {
x = true;
}
}
if (x == true) {
console.log("Data is sent to DB");
return true;
someFunctionToContinueSendingTheDate();
} else {
console.log("Data is INVALID")
someFunctionToStop();
return false;
}
}</script>
I've read the answers from several users here, and my intention is to check if the email is already on the DB.
So my code is the following
**HTML CODE**
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input id="fnam" name="firstname" class="profile-input form-control" type="text" placeholder="First Name" autocomplete="off" maxlength="25" required />
<!-- <input id="fullname" name="fullname" class="form-control" placeholder="Full Name" required="" type="text">-->
</div>
</div>
</div>
</fieldset>
<fieldset>
<!-- Prepended text Last Name-->
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input id="lastname" name="lastname" class="profile-input form-control" type="text" placeholder="Last Name" autocomplete="off" maxlength="25" required />
<!-- <input id="fullname" name="fullname" class="form-control" placeholder="Full Name" required="" type="text">-->
</div>
</div>
</div>
</fieldset>
<fieldset>
<!-- Prepended text Email-->
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
<input id="email" name="email" class="profile-input form-control" type="email" placeholder="Email" autocomplete="off" maxlength="50" required/>
<!-- <input id="email" name="email" class="form-control" placeholder="Email" required="" type="text">-->
</div>
</div>
</div>
JS/ AJAX
function chemail(inputText) {
var email1 = $("#email").val();
var x = document.forms["myappForm"]["email"].value;
var datastring = '$email='+ x; // get data in the form manual
//var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
// if(inputText.value.match(mailformat)){
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
var msgp="Invalid Email. Ex: abc#ggggg.com";
document.getElementById("msgreturn").style.color= "red";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "red";
document.myappForm.email.focus();
return false;
}
else
{
document.myappForm.email.focus();
var msgp="Email verified";
document.getElementById("msgreturn").style.color= "green";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "green";
return true;
$("span.loading").html("<img src='images/ajax_fb_loader.gif'>");
$("span.validation").html("");
var datastring = '&email='+ x;
$.ajax({
type: "POST", // type
url: "check_email.php", // request file the 'check_email.php'
data: datastring, // post the data
success: function(responseText) { // get the response
if(responseText == 1) { // if the response is 1
$("span.email_val").html("<img src='images/invalid.png'> Email are already exist.");
$("span.loading").html("");
} else { // else blank response
if(responseText == "") {
$("span.loading").html("<img src='images/correct.png'> You are registred.");
$("span.validation").html("");
$("form input[type='text']").val(''); // optional: empty the field after registration
}
}
}
}
}
and the check_email.php
<?php require_once("../../php_includes/dbconnect.php");
$email = $_POST['x'];
$query = mysql_query("SELECT 'email' FROM 'members' WHERE 'email' = '$email'");
if(mysql_num_rows($query) == 1) { echo '1'; } else { echo '1'; }
?>
So the sources are all working, I've set some alerts inside of ajax but it didn't worked, can you please tell me where am I making the mistake , I'm following the example from other users from this site, however can't reach a solution.
Assuming that you have directly copied your code, the error can be found by checking indentation. I would suggest, BTW, that you make your editor replace tabs with spaces, as tabs may not show the spacing correctly on any other system (such as SO!).
function chemail(inputText) {
var email1 = $("#email").val();
var x = document.forms["myappForm"]["email"].value;
var datastring = '$email='+ x; // get data in the form manual
//var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
// if(inputText.value.match(mailformat)){
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
var msgp="Invalid Email. Ex: abc#ggggg.com";
document.getElementById("msgreturn").style.color= "red";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "red";
document.myappForm.email.focus();
return false;
}
else
{
document.myappForm.email.focus();
var msgp="Email verified";
document.getElementById("msgreturn").style.color= "green";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "green";
return true;
// HERE'S THE PROBLEM!!! The following code never gets executed. Missing parenthesis.
$("span.loading").html("<img src='images/ajax_fb_loader.gif'>");
$("span.validation").html("");
var datastring = '&email='+ x;
$.ajax({
type: "POST", // type
url: "check_email.php", // request file the 'check_email.php'
data: datastring, // post the data
success: function(responseText) { // get the response
if(responseText == 1) { // if the response is 1
$("span.email_val").html("<img src='images/invalid.png'> Email are already exist.");
$("span.loading").html("");
} else { // else blank response
if(responseText == "") {
$("span.loading").html("<img src='images/correct.png'> You are registred.");
$("span.validation").html("");
$("form input[type='text']").val(''); // optional: empty the field after registration
}
}
}
}
} // <--- this parenthesis is in the wrong place.
Another thing that should tip you off to the problem is to use the Network tab in the web console. You can use this to see the traffic between the browser and the server; in this case, you would find that there was no request made to the PHP script.
Addendum:
I believe datastring should be an object, not an url encoding. In other words,
var datastring = {email: x};
where x = $('#email').val();
For what it's worth, since you're using JQuery for your ajax, it would be more concise to change things like
document.getElementById("msgreturn").style.color= "red"; to $('#msgreturn').css('color','red');
I am trying to validate user to enter a unique mobile number and email id.
It is checking and showing result mobile/email exist or not but if it exists still the form is submitting. Since I am new to jQuery validation I am not able to figure out how I should do it correctly nor can I find a perfect tutorial to do it in a right way.
Here is my code, I know lots of mistakes would be there and I apologize for those small mistakes.
On my form I have given On blur function to check mobile number and email
From these two functions I am checking in database if exist or not
function check_availability() {
//get the mobile number
var main = $('#main').val();
//use ajax to run the check
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
}
});
}
function email_availability() {
//get the email
var main = $('#email_tuitor').val();
//$email = urldecode("[email]")
//use ajax to run the check
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
}
});
}
This is the jquery ajax form submission is it possible to do every validation on blur ?
$(document).ready(function() {
$('.error').hide();
$("#next_tutor").click(function() {
$('.error').hide();
var main = $("#main").val();
if (main == "") {
$("label#main_error").show();
$("input#main").focus();
return false;
}
var name = $("#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email_tuitor = $("#email_tuitor").val();
if (email_tuitor == "") {
$("label#email_tuitor_error").show();
$("input#email_tuitor").focus();
return false;
}
var password_tuitor = $("#password_tuitor").val();
if (password_tuitor == "") {
$("label#password_tuitor_error").show();
$("input#password_tuitor").focus();
return false;
}
var tutor = $("#tutor").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'main=' + main + '&name=' + name + '&email_tuitor=' + email_tuitor + '&password_tuitor=' + password_tuitor + '&tutor=' + tutor;
// AJAX Code To Submit Form.
//alert(dataString);
//die;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tutor/tutor_sub_ses",
data: dataString,
cache: false,
success: function(result) {
//alert(result);
$("#abc").hide();
$("#tutorreg2").slideToggle("slow").show();
}
});
return false;
});
});
<form class="form-horizontal" action="#">
<div class="form-group">
<div class="col-sm-8 text-center">
<h2 class="text-warning">Tutor Registration</h2>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" value="tutor" style="display:none" id="tutor">
<input type="text" class="form-control" id="name" placeholder="Name">
<label id="name_error" class="error" for="name"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control phone" id="main" placeholder="Mobile Number *This will be the key to your account*" onBlur="check_availability()">
<span id="mobile_availability_result"></span>
<label id="main_error" class="error" for="main"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control" id="email_tuitor" placeholder="Email" onBlur="email_availability()">
<span id="email_availability_result"></span>
<label id="email_tuitor_error" class="error" for="email_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="password" class="form-control" id="password_tuitor" placeholder="Password">
<label id="password_tuitor_error" class="error" for="password_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 text-right">
<button type="submit" class="btn btn-warning" id="next_tutor">Next</button>
</div>
</div>
</form>
The quick way will be to use a global switch to enable sending the form. I would to it this way:
Create global variables with default values
var mobileApproved = false, emailApproved = false;
Check status and prevent sending if value is false in click handler
$(document).ready(function() {
...
$("#next_tutor").click(function() {
if (!mobileApproved || !emailApproved) {
return false;
}
...
})
...
})
In your check functions manage approved status after each ajax response
...
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
mobileApproved = true;
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
mobileApproved = false;
}
});
...
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
emailApproved = true;
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
emailApproved = false;
}
});
In order to stop the form from submission. You can keep a flag lets say formvalid.
Keep formValid as false initially. Based on your blur function, make it true if email and mobile are available else keep it false. In your form submission, put an if condition to check , if formvalid is true or not. If true then process with form submission else stop and throw error.
Here is my form that i created using HTML and Bootstrap
<div class="col-sm-7 slideanim">
<form id="frm-post-comment" name="frm-post-comment" method="post" action="#">
<input type="hidden" name="the-comment" value="true">
<div class="row">
<div class="col-sm-6 form-group">
<input class="form-control" name="name" placeholder="Name" type="text">
</div>
<div class="col-sm-6 form-group">
<input class="form-control" name="email" placeholder="Email" type="email">
</div>
</div>
<textarea class="form-control" name="comments" placeholder="Comment" rows="5"></textarea>
<br>
<div class="row">
<div class="col-sm-12 form-group">
<button id="comment-post" class="btn btn-info pull-right" type="submit">Send</button>
</div>
</div>
</form>
</div>
I then want to validate the form inputs using JQuery, here is the validation code
$(document).ready(function() {
$("#comment-post").click(function() {
submitComment();
$("#comment-pst-alert").show();
$("html,body").animate({
scrollTop: 0
}, "slow");
});
});
function submitComment() {
var msg = "";
var name = $("#name").val();
var email = $("#email").val();
var comments = $("#comments").val();
var re = /^[A-Za-z]+$/;
if (name == "" || name.length < 3) {
msg += "*Please enter a valid name,it must be longer than three characters.<br>";
}
if (!re.test(name)) {
msg += "*Please enter a valid name,it must not contain numbers.";
}
var chkEmail = /^[a-z0-9._%-]+#[a-z0-9.-]+\.[a-z]{2,4}$/;
if (email == "") {
msg += "<br>*Please enter an email address.";
}
if (email.length < 8) {
msg += "<br>*Email address cannot be less than 8 characters";
}
if (email.search('#') == -1) {
msg += "<br>*Email must have a #,please enter a valid email address.";
}
if (comments == "") {
msg += "<br>*Please enter a comment.";
}
if (comments.length > 70) {
msg += "<br>*The comment can not exceed 70 characters";
}
if (msg != "") {
$("#comment-pst-alert").addClass("alert-danger");
$("#comment-pst-alert").children("strong").text("Warning");
$("#comment-pst-alert").children("p").html(msg);
}
else {
$("#name").val("");
$("#email").val("");
$("#comments").val("");
var closeAlert = $("<a/>", {
"class": "close",
"data-dismiss": "alert",
"text": "x"
});
$("#comment-pst-alert strong").before(closeAlert);
$("#comment-pst-alert").removeClass("alert-danger");
$("#comment-pst-alert").addClass("alert-success");
$("#comment-pst-alert").children("strong").text("Success");
msg += "<br>You have successfully submitted your details, you will here from us within 24 hours.";
$("#comment-pst-alert").children("p").html(msg);
}
$("#comment-pst-alert").show();
}
I have a bootstrap alert control that is initially hidden using CSS. If there is an error in the user input, I show the alert control and add the relevant class to it. If there is no error, I want to remove the former class and add a success class to the alert control and then I want to submit the input and add the data into the database using PHP.
$connection = mysql_connect('localhost', 'root', 'root');
if ($connection) {
if ($_POST["name"] != "" ||
$_POST["email"] != "" ||
$_POST["comments"] != "") {
mysql_select_db("smart_hustle_comments") or die("could not select table ".mysql_error());
$name = $_POST["name"];
$email = $_POST["email"];
$comment = $_POST["comments"];
$sql = "INSERT INTO user_comments VALUES('$name','$email','$comment')";
$query = mysql_query($sql);
}
}
I am getting no error on console nor on PHP,the form submits but does not execute the JQuery validation, please help.
Your jquery validation is skipped because you submit form simultaneously with validation.
Change your button type to button type instead submit, after successfull validation use $('#frm-post-comment').submit(); to apply form.
I have a login form that, when completed, sends users to a page with a JavaScript generated URL (allowing me to pass a JavaScript variable to my PHP script using $_GET). However, in order to do that, the Login button is currently 'type="button"'. While everything works, it means that users cannot login by hitting Enter; they must actually click the Login button. Is there a way I can "Submit" the form, while still having it point to the JavaScript generated URL?
This seems like a pretty basic concept, which tells me I might be approaching it the wrong way to begin with. Any guidance is appreciated.
HTML:
<form name="login">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
</form>
JavaScript:
function check(form) {
var userCredentials = [["jsmith", "smithpassword", "John Smith"], ["jdoe", "doepassword", "Jane Doe"]];
var credCheck = 0;
for (var i = 0; i < userCredentials.length; i++) {
if (userCredentials[i][0] == form.user_id.value) {
credCheck += 1;
var displayName = userCredentials[i][2];
if (userCredentials[i][1] == form.pswrd.value) {
window.open("home.php?display_name=" + displayName, "_self");
} else {
alert('The username and password do not match.');
return false;
}
}
}
if (credCheck == 0) {
alert('The username entered is not valid.');
return false;
} else {
return true;
}
}
Instead of opening php page via javascript, you need to change the form action dynamically to point to your generated url.
HTML:
<form name="login">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="submit" onclick="check(this.form)" value="Login"/>
</form>
JavaScript: (line 9 & 10 changed)
function check(form) {
var userCredentials = [["jsmith", "smithpassword", "John Smith"], ["jdoe", "doepassword", "Jane Doe"]];
var credCheck = 0;
for (var i = 0; i < userCredentials.length; i++) {
if (userCredentials[i][0] == form.user_id.value) {
credCheck += 1;
var displayName = userCredentials[i][2];
if (userCredentials[i][1] == form.pswrd.value) {
form.action = "home.php?display_name=" + displayName;
return true;
} else {
alert('The username and password do not match.');
return false;
}
}
}
if (credCheck == 0) {
alert('The username entered is not valid.');
return false;
} else {
return true;
}
}
You could try:
<form name="login" onsubmit="check(this)">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="submit" value="Login"/>
</form>