I am trying to incorporate this code to allow me to register a user after their details are given, and then load the new page, all done using AJAX.
Step 1:
User registers enters their details in the form within register.php. Upon submit using the input with the ID "reg-submit", the details are passed to click.js.
Step 2:
If the user is successful, the information is processed in click.js, and prepared via ajax to be passed to usersubmit.php for DB insertion.
Step 3:
data has been successfully inserted into the DB and next-page.php loads into the "#main-content" div (located within index.php).
To help keep things in context. All pages are loaded within the #main-content div within index.php. They are all loaded via the same function used that you will see in the click.js portion upon ajax success. Register.php is simply one of the pages that loads within this div.
I need the registration to happen, and then load the next page while all of the back end database information is inserted appropriately.
register.php
<script src="js/click.js"></script>
<form action="click.js" method="post">
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" /><br>
<label for="last_name" >Last Name:</label>
<input type="text" id="last_name" name="last_name" /><br>
<label for="username">Username:</label>
<input type="text" id="username" name="username" /><br>
<label for="password">Password:</label>
<input type="text" id="password" name="password" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<button type="submit" id="reg-submit" name="submit">Submit</button><br>
</form>
click.js
$(document).ready(function(){
$('#reg-submit').click(function() {
var firstName = $('#first_name').val();
var lastName = $('#last_name').val();
var userName = $('#username').val();
var password = $('#password').val();
var email = $('#email').val();
var dataString = 'name1=' + firstName + '&lastname1=' + lastName + '&user1=' + userName + '&password1=' + password + '&email1=' + email;
if (firstName == "" || lastName == "" || userName == "" || password == "" || email == "") {
alert('missing some information');
} else {
$.ajax({
type: "POST",
url: "usersubmit.php",
data: dataString,
cache: false,
success: function(){
$('#main-content').load('php/next-page.php').hide().fadeIn('slow');
}
});
};
return false;
});
});
the DB connection takes place within the users_db.php.
usersubmit.php
<?php
include 'users_db.php';
$first1=$_POST['name1'];
$last1=$_POST['lastname1'];
$username1=$_POST['user1'];
$pass1=$_POST['password1'];
$email01=$_POST['email1'];
$userinfo = $conn->prepare("INSERT INTO registered_users (FirstName, LastName, Username, Password, Email) VALUES ('$first1', '$last1', '$username1'', '$pass1', '$email01')");
$userinfo->execute();
$conn = null;
?>
Much appreciated!
If you see any other problems I may have here outside of the form simply not submitting, feel free to point them out.
Change the
<input type="button" id="reg-submit" name="submit" value="Submit"/>
to
<button type="button" id="reg-submit" name="submit">Submit</button>
In order to avoid the form submitting and te ajax call will be triggered.
Add a return false; to the end of the js function to prevent the form from submitting and to allow the ajax call to actually be made.
Related
I'm designing a login form where the username and password get validated. If the user inputs are correct then I need to navigate to a different page else display an error message. The problem I'm facing is that I'm unable to navigate to another page after validation. The only way I can switch to another page is by entering the html file's name directly in the form action attribute. Here is my code:
<form id="form" action="submit.php" target="_blank" method="post" >
<div class="container">
<label for="uname"><b>Username</b></label>
<input id="usrname" type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input id="passwrd" type="password" placeholder="Enter Password" name="psw"
required>
<button type="submit" onClick="validateForm()">Login</button>
</div>
</form>
<script>
function validateForm() {
var un = document.querySelector('#usrname').value;
var pw = document.querySelector('#passwrd').value;
var username = "admin";
var password = "pass";
if ((un == username) && (pw == password)) {
alert('You are successfully logged in');
location.replace("https://google.com")
}
else {
alert("Login was unsuccessful, please check your username and password");
return false;
}
}
</script>
Try this:
In the if statement, replace this:
location.replace("https://google.com")
And try using this:
window.location.href= "https://google.com"
I am trying to put together a simple login prompt for a bit of in house testing and I have found myself stuck. I have the login prompt made via HTML and am trying to send it off via xmlhttprequest. Here is my JS code:
var xhr = new XMLHttpRequest();
function loginResults() {
var loginUser = document.getElementById("username").value;
var loginPass = document.getElementById("password").value;
//console.log(loginUser + loginPass);
xhr.open("post", "https://test.com/api/login/");
var loginData = "username=" + loginUser + "&password=" + loginPass
xhr.send(loginData);
//console.log(loginData);
xhr.addEventListener("readystatechange", processRequest, false);
}
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
}
The issue is that the xhr.send completely fails using this method. However if I replace the variables sent with the plain text then everything works fine. Like this:
var loginData = "username=" + "test#test.com" + "&password=" + "test1234"
What is the difference between pulling the info via the form data and having the login hard coded like that? The request payload is exactly the same in both instances.
EDIT
Here is the gist of my HTML form:
<form name="isLogin" id="isLogin" onSubmit="loginResults()" method="post">
<div class="container">
<label for="username"><b>Email</b></label>
<input type="text" id="username" placeholder="Enter Email" name="username" required>
<label for="password"><b>Password</b></label>
<input type="password" id="password" placeholder="Enter Password" name="password" required>
<button id="submitLogin" type="submit">Login</button>
The reason the request gets cancelled is you aren't intercepting the standard form submission. When you click the Login button, Chrome fires off the AJAX request, then also submits the form. Since this leads to a page load, Chrome cancels the AJAX request.
What you need to do is prevent the default event handling. A clean way to do this is to add the submission handling in your script:
document.getElementById("isLogin").onsubmit = function(e) {
e.preventDefault();
// AJAX here
console.log("form submission intercepted");
};
<form name="isLogin" id="isLogin" method="post">
<div class="container">
<label for="username"><b>Email</b></label>
<input type="text" id="username" value="test#test.com" name="username" required>
<label for="password"><b>Password</b></label>
<input type="password" id="password" value="test1234" name="password" required>
<button id="submitLogin" type="submit">Login</button>
</div>
</form>
You need to escape values before concatenating them to the URL querystring:
var loginUser = encodeURIComponent(document.getElementById("username").value);
var loginPass = encodeURIComponent(document.getElementById("password").value);
Secondly, i wouldn't recommend passing password directly through querystring.
The secure way to pass it is preferably salted-and-hashed.
I have written the below code to make a simple form for validation of form inputs through javascript. Here username and passwords are written in the JS code, but it still shows alert message of the else loop even if giving correct credentials on the form.
Please Help?
var user = document.getElementById('username')
var pass = document.getElementById('password')
function user1() {
if (user == "admin" && pass == "root") {
window.open("javascript_trial.html")
alert('correct username')
} else {
alert('incorrect username or password')
}
}
<form>
<input type="text" name="username" Placeholder="enter username"><br>
<input type="password" name="password" Placeholder="enter password"><br>
<button onclick="user1()">Submit</button>
</form>
There are a few errors here:
You need to get the values of your inputs
You want to get those values when the button is clicked. Your code is grabbing them only when the page loads. Move the variable assignment into your function
You didn't give the elements ID attributes
function user1() {
var user = document.getElementById('username').value
var pass = document.getElementById('password').value
if (user == "admin" && pass == "root") {
window.open("javascript_trial.html")
alert('correct username')
} else {
alert('incorrect username or password')
}
}
<form>
<input type="text" name="username" id="username" Placeholder="enter username"><br>
<input type="password" name="password" id="password" Placeholder="enter password"><br>
<button onclick="user1()">Submit</button>
</form>
Also note that a button's default type is submit which will submit your form and reload the page after the alert is shown when clicked, so you might want to change that to type="button" to prevent that.
I'm currently creating a mobile website. I'm using jquery mobile.
I've already implemented the login and I'm now working on the registration.
On the login page i've got a simple . On the registration I am then logging the inputs, but it seems that the fields "username" and "password" are empty, even though i've entered some text. This problem doesn't occur after refreshing the page or if I load the page directly from the address bar.
Pageinit is being triggered.
I've deleted the cache but the problem is still there. Does anyone know why this is happening?
Here my code:
<!-- PAGE LOGIN -->
<div data-role="page" id="pageregistration">
<div data-role="content">
<input name="username" id="username" type="text" size="45" maxlength="45" placeholder="Username">
<input name="email" id="email" type="text" size="45" maxlength="45" placeholder="Email">
<input name="password" id="password" type="password" size="45" maxlength="45" placeholder="Password">
<input name="passwordConfirm" id="passwordConfirm" type="password" size="45" maxlength="45" placeholder="Confirm Password">
<button id="register">Create Account</button>
</div>
<script>
$('#pageregistration').on('pageinit', function()
{
$("#register").click(function(e)
{
e.preventDefault();
var username = document.getElementById('username').value;;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var passwordConfirm = document.getElementById('passwordConfirm').value;
console.log("Username: " + username + ", email: " + email + ", password: " + password + " - " + passwordConfirm);
});
});
</script>
</div>
Try with this because pageinit is triggered on the page being initialized, after initialization occurs.
Means you are getting to the registration page from somewhere (Other page)
$(document).on("pageinit", "#pageregistration", function(event) {
// rest of the code
});
The problem was found thanks to Omar. I changed the IDs and everything worked as desired.
I have an HTML form that I would like to make interact with some JavaScript:
...
<form name="signup">
<label id="email" for="email" placeholder="Enter your email...">Email: </label>
<input type="email" name="email" id="email" />
<br />
<input type="submit" name="submit" id="submit" value="Signup" onclick="signup()"/>
</form>
...
I have some JavaScript that I want to take the entered email address and store it in an array (it is currently inline with my HTML hence the script tags):
<script type="text/javascript" charset="utf-8">
var emailArray = [];
function signup(){
var email = document.signup.email.value;
emailArray.push(email);
alert('You have now stored your email address');
window.open('http://google.com');
console.log(emailArray[0]);
}
</script>
I was hoping that this simple script would store the email in emailArray but the console remains empty throughout the execution.
What is wrong with this code?
You have two problems.
Your form is named signup and your global function is named signup. The function is overwritten by a reference to the HTML Form Element Node.
Your submit button will submit the form, causing the browser to leave the page as soon as the JS has finished (discarding all the stored data and probably erasing the console log)
Rename the function and add return false; to the end of your event handler function (the code in the onclick attribute.
Please rename your function name (signup) or Form Name (signup),
because when you are try to access document.signup......
It'll make a type error like, object is not a function
Try below Code,
<script type="text/javascript">
var emailArray = [];
function signup() {
var theForm = document.forms['signupForm'];
if (!theForm) {
theForm = document.signupForm;
}
var email = theForm.email.value;
emailArray.push(email);
console.log(emailArray[0]);
}
</script>
<form name="signupForm">
<label id="email" for="email" placeholder="Enter your email...">Email: </label>
<input type="email" name="email" id="email" />
<br />
<input type="button" name="submit" id="submit" value="Signup" onclick="signup(); return false;"/>
</form>
The problem that is given is that the form name is "signup" and the function is "signup()", then the function is never executed (this is better explained in this answer). If you change your form name or your function name everything should work as expected.
try this code :
<form name="test">
<label id="email" for="email" placeholder="Enter your email...">Email: </label>
<input type="text" name="email" id="email" onBlur=/>
<br />
<input type="button" name="submit" id="submit" value="Signup" onclick="signup()"/>
</form>
<script type="text/javascript" charset="utf-8">
var emailArray = [];
function signup(){
var email = document.getElementById('email').value;
emailArray.push(email);
alert('You have now stored your email address');
window.open('http://google.com');
console.log(emailArray[0]);
return false;
}
</script>
As suggested in the comments, just change your email variable to:
var email = document.getElementById('email').value;
then just push it to your emailArray
EDIT
You'll need to rename the ID of your label. The reason it's currently not working is because the value being returned is that of the first element with the id of email (which is your label, and undefined).
Here's a Fiddle
I would propose two improvements to your code:
Put your javascript right after the <form> element in order to be sure that dom element exist in the document
Attach click handler using addEventListener method. Read more here.
Email:
var emailArray = []; function signup(){ var email = document.getElementById('email').value; emailArray.push(email); alert('You have now stored your email address'); window.open('http://google.com'); console.log(emailArray[0]); return false; } document.getElementById("submit").addEventHandler('click', signup, false);