I am trying to use JavaScript to redirect to a PHP page on my site, however, when I do it, nothing happens, apart from the alert boxes if I do not fill in the parameters. Is there something I am doing wrong?
document.getElementById("submit").onclick = check;
function check()
{
if(document.getElementById("name").value == "")
alert("The field 'Name' is required.");
else if (document.getElementById("message").value == "")
alert("The field 'Message' is required");
else
window.location.href = "scripts/main/contact.php?msg=" + document.getElementById("message").value;
}
Your default form action takes place overriding your redirect. Return false from the handler to prevent it from taking place:
function check()
{
if(document.getElementById("name").value == "")
alert("The field 'Name' is required.");
else if (document.getElementById("message").value == "")
alert("The field 'Message' is required");
else
window.location.href = "scripts/main/contact.php?msg=" + document.getElementById("message").value;
return false; // <------ here
}
Related
I have added a loader on my phonegap app on login button it works. but when Some alert occurs like password mismatch or invalid user, The loader doesn't stops. I have added my loader on html page, and want to stop at my Authentication js page in which alerts box are there in my html page to hide on next page I am using
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#loading').hide();
});
</script>
how to hide my loader on js page alerts
if(Server == "" || UserName == "" || UserPass == "")
{
if(Server == "")
{
alert("Please enter server address");
}
if(UserName == "")
{
alert("Please enter User Name");
}
if(UserPass == "")
{
alert("Please enter Password");
}
}
else
{
strUrl="https://" + Server + ":1000";
//alert("Test"+strUrl);
sessionStorage.setItem("Server",Server);
window.localStorage.setItem("serUrl", strUrl);
window.localStorage.setItem("serUrl", strUrl);
window.localStorage.setItem("Server", Server);
strSerUrl="http://" + Server + ":8888/";
//alert(strSerUrl);
window.localStorage.setItem("ServerUrl", strSerUrl);
var DivId=sessionStorage.getItem('DivId');
DivId=window.localStorage.getItem("DivId")
// alert(DivId);
Identifier=Identifier+"_"+DivId;
//alert("Create Session1"+Identifier);
window.localStorage.setItem("Identifier", Identifier);
sessionStorage.setItem("Identifier",Identifier);
//alert("above create session")
services.CreateSession(Identifier, SystemID, UserName, UserPass, ConnectionEstablished, AuthenticationFailed);
}
}
function ConnectionEstablished(ResponseData) {
if (ResponseData != "")
{
//alert("resp"+ResponseData)
AuthenticationSuccess(ResponseData);
}
else
alert("Username or Password is incorrect!");
}
you can make the following change to your function to make it work:
function ConnectionEstablished(ResponseData) {
if (ResponseData != "")
{
//alert("resp"+ResponseData)
AuthenticationSuccess(ResponseData);
}
else
{
$('#loading').hide(); //hide the loader!
alert("Username or Password is incorrect!");
}
}
Try if it works!
In my login script when the username and password are both correct it must go to the next page (main/menu page) of the intel XDK.
My problem is how or what code can I use to call the next page whenever the username and password is correct (login successful)?
function validateForm() {
var formUsername = document.forms.login.username.value;
var formPassword = document.forms.login.password.value;
var MINLENGTH = 5;
// Validate username and password
if (formUsername === null || formUsername === "") {
alert("Username must be filled out");
}
else if (formPassword === null || formPassword === "") {
alert("Password must be filled out");
}
else if (formUsername.length < MINLENGTH || formPassword.length < MINLENGTH) {
alert("The minimum length of username and password at least " + MINLENGTH);
}
else if(formUsername == 'admin' && formPassword == 'admin'){
alert('welcome');
//this is where should i put the code to go at the next page of the XDK API.
return;
}
alert("Login failed!!!");
}
got it guys..
it will be.. like this ..
else if(formUsername == 'admin' && formPassword == 'admin'){
alert('welcome');
activated_page("#menu");
return;
}
So my script perfectly checks whether username is free or not but regardless of that when user submits all forms he is able to register. I need a way to prevent user from registering if username is taken. Here is the code:
index.php
$("#username").keyup(function(){
var val=$("#username").val();
$("#address").html("Your address will be askfolio.com/" + val);
$("#freeu").html("<img src='css/ajax-loader.gif' style='margin-left:-75px;'>");
if (val != ''){
$.ajax({
url:"s/ufree.php",
method:"POST",
data:$("#username"),
success:function(data){
if (data == 1){
$("#freeu").html("<img src='css/accept.png' style='float:left;padding-right:65px;'>");
$("#reg-error").css("display","none");
}else{
$("#freeu").html('');
$("#reg-error").css("display","block");
$("#reg-error").html('Username is already taken, try another.');
$("#username").focus();
return false;
}
}
});
}else {
$("#freeu").html('');
}
});
function Users_Registration()
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $("#name").val();
var lastname=$("#lastname").val();
var username = $("#username").val();
var remail = $("#remail").val();
var rpass = $("#rpass").val();
var day=$("#day").val();
var month=$("#month").val();
var year=$("#year").val();
if(name == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your name in the required field.');
$("#name").focus();
}
else if(lastname == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html(' Please enter your Last Name in the required field.');
$("#lastname").focus();
}
else if(username == ""){
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your desired username to proceed.');
$("#username").focus();
}
else if(remail == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your email address to proceed.');
$("#remail").focus();
}
else if(reg.test(remail) == false)
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter a valid email address to proceed.');
$("#remail").focus();
}else if (rpass == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter a valid password to proceed.');
$("#rpass").focus();
}
else if (day == ""){
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a day to proceed.');
$("#day").focus();
}else if (month == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a month to proceed.');
$("#month").focus();
}else if (year == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a year to proceed.');
$("#year").focus();
}
else
{
var dataString = 'name='+ name + '&lastname='+ lastname + '&username='+ username + '&rpass='+ rpass + '&remail='+ remail + '&year=' + year + '&month=' + month + '&day=' + day +'&page=signup';
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
cache: false,
beforeSend: function()
{
$("#reg-error").html('<br clear="all"><div style="padding-left:115px;"><font style="font-family:Verdana, Geneva, sans-serif; font-size:12px; color:black;">Please wait</font> <img src="images/loadings.gif" alt="Loading...." align="absmiddle" title="Loading...."/></div><br clear="all">');
},
success: function(response)
{
$("#reg-error").html("Loading");
var username="<?php echo $loguser; ?>";
window.location=username;
}
});
}
}
ufree.php
<?php
include "db.php";
if (isset($_POST['username'])) {
$username=$_POST['username'];
$sql=mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($sql) == 0) {
echo "1";
}else {
echo "<div style='padding-top:4px;'>username is taken</div>";
}
}
?>
Apart from the SQL Injection vulnerability that you have in your sql queries, your approach to username check is somewhat redundant. By checking the username upon every character input you add extra load to the browser and to your server.
I suggest you combine the two processes in one step meaning you do the username check and register in the same place. In your Register.php file check the username availability right before the registration and if the username is taken display a proper message and if not do the registration.
Goes without saying but regardless of the javascript validation, your server still needs to be checking that the username is available at point of registering, since anyone can disable or manipulate the javascript.
Also as Hamed states, your php code is highly vulnerable. At the very least, you should use the following prior to using it in your sql:
$username = mysql_real_escape_string( $_POST[ 'username' ] );
That said, for usability, what you need to do is add an onsubmit function to your form, which checks if the username is valid or not prior to submitting. (summarised your code for simplicity)
var validUser = false;
$("#username").keyup(function(){
var val=$("#username").val();
validUser = false;
if (val != ''){
$.ajax({
url:"s/ufree.php",
method:"POST",
data:val,
success:function(data){
if (data == 1){
validUser = true;
}else{
$("#username").focus();
return false;
}
}
});
}else {
$("#freeu").html('');
}
function formsubmit()
{
if( !validUser )
{
alert( 'Username is already taken, try another' );
return false;
}
return true;
}
Then in your form:
<form action="whatever" onsubmit="return formsubmit();">
...
</form>
Once of my favorite jQuery plugin is the validation eng.
https://github.com/posabsolute/jQuery-Validation-Engine
It has very nice validation for doing just what you are looking for. It does all kinds of fields including inline ajax for username check. If the response from ajax call is not true, then the form won't submit. I use it for my signup forms. Once the user goes to the next field it validates, if it doesn't pass i.e. the username is not available, it will say username not available in red. The form won't submit.
It's not hard to setup. Here is a demo of the ajax. Note it won't actually validate on this demo site but it's an example. You can see how it won't submit though if it's blank or not validated. It's very customizable.
http://www.position-relative.net/creation/formValidator/demos/demoAjaxSubmitPHP.html
Oh course take care of any mysql security issues and check to make sure dupes can't be entered into the database as well.
I am trying to validate my company email-id's in sign up form...so that the form accepts only my company mail id...so now whats the problem here is after validating(ie; when we click submit button then we get an alert message) the form is getting refreshed and the entered values are cleared...so any help or suggestions so that it is not refreshed??thanks in advance...
My Javascript method is:
function submitAlbum() {
var frm = document.getElementById("frmRegistration");
//validateEmail(document.getElementById('email').value);
var email = document.getElementById('email').value;
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
// alert('Submission was successful.');
var r = confirm("Are You Sure You Want to add your details.");
if (r == true) {
frm.action = "signUpServlet?formidentity=doRegistration&checkboxStatus=" + checkboxStatus;
frm.submit();
}
}
else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
return false;
}
}
else {
document.getElementById('email').focus();
alert('Not a valid e-mail address.');
return false;
}
}
I think this will do the job.
<input type = "email" pattern ="^[a-z0-9._%+-]+#bdisys.com">
Check this bin
http://jsbin.com/dew/5/edit
You should bind your validation method to the submit event of your form.
Inside the validation method, stop the event to propagate if the field is invalid, or let it bubble if it's ok.
var frm = document.getElementById("frmRegistration");
frm.addEventListener('submit', validate, false);
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function validate(event) {
// validateEmail
var email = document.getElementById('email').value;
var confirmed = false;
if (re.test(email)) {
confirmed = true;
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
confirmed = confirm("Are You Sure You Want to add your details.");
}
} else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
}
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
return false;
}
}
I suggest you to use jQuery to make your code simplier and before all portable.
First off, I don't know much about JS so please be patient with me.
I found this free validation JS and implemented it into my website, however, after a successful validation it doesn't tell you the form has been submitted.
My question is, is it possible to make this validation summon Apprise.js alert on a successful validation? Apprise
$(document).ready(function(){
//global vars
var form = $("#ContactForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var subject = $("#subject");
var subjectInfo = $("#subjectInfo");
var message = $("#message");
//On blur
name.blur(validateName);
email.blur(validateEmail);
subject.blur(validateSubject);
//On key press
name.keyup(validateName);
subject.keyup(validateSubject);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() & validateEmail() & validateSubject() & validateMessage())
return true
else
return false;
});
//validation functions
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
email.removeClass("error");
emailInfo.text("");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else{
email.addClass("error");
emailInfo.text("Please type a valid e-mail address!");
emailInfo.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("Name must be atleast 4 letters (include last name)!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("");
nameInfo.removeClass("error");
return true;
}
}
function validateSubject(){
//if it's NOT valid
if(subject.val().length < 4){
subject.addClass("error");
subjectInfo.text("Subject must be atleast 4 characters!");
subjectInfo.addClass("error");
return false;
}
//if it's valid
else{
subject.removeClass("error");
subjectInfo.text("");
subjectInfo.removeClass("error");
return true;
}
}
function validateMessage(){
//it's NOT valid
if(message.val().length < 1){
message.addClass("error");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
});
You can add a prompt dialog box alert('Your Email has been sent.'); before return true, in form.submit function.