Trying to submit html form data via xmlhttprequest - javascript

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.

Related

JSON Post request is showing 200 success, but script is not executing

FrontEnd
this gets the name, age, city puts it in a JSON format and sends it to localhost:5100/getJson which is my backend.
<form>
<div class="form-group">
<label for="text">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" name="name">
</div>
<div class="form-group">
<label for="text">Age:</label>
<input type="text" class="form-control" id="age" placeholder="Age" name="age">
</div>
<div class="form-group">
<label for="text">City:</label>
<input type="text" class="form-control" id="city" placeholder="Enter city" name="city">
</div>
<button onclick = "MyFunction()" id = "submitButton" type="submit" class="btn btn-default">Submit</button>
<p id = "demo">
</p>
<script>
function MyFunction() {
var name = document.getElementById("name").value
var age = document.getElementById("age").value
var city = document.getElementById("city").value
jsonRequest = {"name":name, "age":age, "city":city}
fetch('http://localhost:5100/acceptJson', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: jsonRequest
}).then(res => res.json())
}
</script>
my backend is a flask server in python.
Backend
app = Flask(__name__)
#app.route('/acceptJson',methods=['GET', 'POST'])
def acceptJson():
jsonData = request.json
name = jsonData['name']
age = jsonData['age']
city = jsonData['city']
postToDatabase(name,age,city)
return "Succesful"
if __name__ == '__main__':
app.run(host = "localhost", port = 5100)
Now when I make the same JSON post request using software like Postman it works, returns 200 and runs the script.
but when I do it through the code, it return 200 and doesn't run the script, so it's clearly something wrong with the POST in the javascript, but I do not understand where it's wrong.
The problem seems to be related to your front-end. In the following answer, I assume your form is submitted by "MyFunction".
In this line of HTML:
<button onclick = "MyFunction()" id = "submitButton" type="submit" class="btn btn-default">Submit</button>
The button is a submit type button. When you click the button, the browser submits the form as usual. With no "action" attribute in the tag, the request is submitted to the webpage you open i.e. no request was sent to the back-end.
The solution can be found in this question: Form not submitting with JS. However, I would suggest another method to do so.
You may add "event.preventDefault();" before you call the function of handling the request or add it to the beginning of the function to stop the form from being submitted automatically in a traditional way.
<button onclick = "event.preventDefault();MyFunction()" id = "submitButton" type="submit" class="btn btn-default">Submit</button>
The reason why to use preventDefault is that it only stop the browser default behavior while other solution (return false) stop the event propagating the DOM.

In react ,how do i force browser to ask for saving password? [duplicate]

This question already has answers here:
Getting Chrome to prompt to save password when using AJAX to login
(6 answers)
Closed 5 years ago.
Hello devs I'm quite new to react and js i'm stuck with this issue any help would be appreciated much, i have a basic form coded in react which takes input from user, when the user click sign in and the credentials are authenticated and validated then the browser should ask user if the user wants to save the password in browser memory.
HTML:
<form onSubmit={this.SignmeIn} autoComplete="on" >
<div className="form-group">
<label htmlFor="email">email</label>
<input type="email" className="form-control" name="email" id="email" placeholder="Email" required="" ref="email" />
</div>
<div className="form-group">
<label htmlFor="password">password</label>
<input type="password" className="form-control" name="password" id="password" placeholder="Password" required="" ref="password" />
<span id="ErrorMessage"></span>
</div>
<div className="form-group">
<button type="submit" className="btn btn-default btn-lg">sign in</button>
</div>
</form>
and here is the SignmeIn function called on submission of form
SignmeIn: function (e) {
e.preventDefault();
var formData = {
"email": this.refs.email.value,
"password": this.refs.password.value
}
$
.ajax({
username:$('input[name=email]').val(),
password:$('input[name=password').val(),
type: 'POST',
url: url + '/signin',
data: formData
})
.done(function (data) {
console.log(data);
if ( typeof data.UserName ==='undefined'||!data.UserName) {
alert('Wrong username or password');
}
else{
alert('welcome ' + data.UserName + "! You are signed in ");
}
})
.fail(function (data) {
console.log('data');
})
i want the browser to display a dialogue asking for user consent whether or not the user want to save the password in browser cache.
My guess there are no react specific changes, adding attribute autocomplete to your form shall fix problem, you've added attribute in camel case instead of lower case, so replacing to lower case shall fix problem.

Can't get AJAX registration form to submit

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.

Force window relocation through a form - JavaScript

I am building a fake login form which should load locally a different url if the user inserts the correct credentials. This is the html code:
<div class="container">
<h2>Login page - Welcome</h2>
<form id="loginForm" onsubmit="subLogin()">
Username: <input id="userName" type="text" name="userName" required><br/>
Password: <input id="passWord" type="password" name="password" required><br/>
<button type="submit" id="login-button" value="Login">Login</button>
</form>
</div>
And this is the javascript where I try to relocate the user via window.location.href = "/index.html".
function subLogin() {
var userName = document.getElementById('userName').value;
var passWord = document.getElementById('passWord').value;
if (userName !== 'mickeymouse' || passWord !== 'DisneyLand') {
alert('Your username or password is not correct');
} else {
window.location.href = 'http://localhost:8000/index.html';
};
};
If the username or password are wrong, but if they are correct the window.location does not work as espected.
Is there a way to solve this issue with pure javascript, or is it better to use anyway a XMLHttp GET Request via ajax? Thanks in advance for your replies!
I managed to solve the issue. I have simply changed the form to:
<form id="loginForm" action="javascript:subLogin()"></form>
I post the code in case that someone may need it in the future. Thanks anyway for your replies!

JQuery Mobile Empty Input Value

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.

Categories