Javascript log in using REST - javascript

I'm trying to make a login using JavaScript which should check the user authentication using a REST service, using a client in java (for testing) it return a string "hej" if it's successful.
My HTML code:
<div class="login">
<form method="POST">
<h1>Login</h1>
<input type="text" name="username" id="username" placeholder="Username" required><br><br>
<input type="password" name="password" id="password" placeholder="Password" required><br><br>
<input type="submit" name="submit" id="submit" onclick="UserAction()">
</form>
</div>
<script src="load_user.js"></script>
And heres my javascript code (load_user.js)
var username;
var password;
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8080/Footballmanagerrestservice/webresources/login", false);
xhttp.setRequestHeader("", User());
xhttp.send();
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
$(location).attr('href', url);
}
}
function User(user, pass) {
username = document.getElementById("username").toString();
username = document.getElementById("password").toString();
var UserAndPass = "?username=" + username + "&password=" + password;
return UserAndPass;
}
I want it to change URL when the login is correct, but it just refreshes the page instead.

use with return in onclick="return UserAction()" function and add return false in end of the
UserAction() function .They will prevent the page refresh .
and window.location.href=url is redirect with new page
Changed JavaScript code
var username;
var password;
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8080/Footballmanagerrestservice/webresources/login", false);
xhttp.setRequestHeader("", User());
xhttp.send();
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href=url
}
return false; //added to prevent page refresh
}
function User(user, pass) {
username = document.getElementById("username").toString();
username = document.getElementById("password").toString();
var UserAndPass = "?username=" + username + "&password=" + password;
return UserAndPass;
}
Changed HTML
<div class="login">
<form method="POST" onsubmit="return UserAction()">
<h1>Login</h1>
<input type="text" name="username" id="username" placeholder="Username" required><br><br>
<input type="password" name="password" id="password" placeholder="Password" required><br><br>
<input type="submit" name="submit" id="submit">
</form>
</div>

use window.location.href = "url_here"; to navigate to new page

Use
window.location.href = "http://localhost:8080/FM3/spil2.jsp";

Please do a redirect, after checking the user credentials to change the URL
window.location.replace("http://stackoverflow.com");
or simulate clicking a link like
window.location.href = "http://stackoverflow.com";

Related

Using the resultant request as a variable in my javascript function

So, i'm using the NPM 'request' library to webscrape the 'URL x'. The '' content inside this 'URL x' is a single line with a youtube video link. So what I'm trying to do is: after my form is submitted, i need to verify the password to match the requirements, than redirect the user to the that youtube video link, inside the '' in the 'URL x', but I don't know how to do it, any ideas ?
// My JS file
var request = require('request');
var url = 'url x';
request(url, function(err, resp, body){
})
function CheckPassword(password){
var psw = /^[a-zA-Z0-9-]\w{1,6}$/;
if (password.value.match(psw)){
alert('Valid password, redirecting ..');
document.location.assign(body);
return false;
}
else{
alert('Invalid password. Try again.');
return true;
}
}
// My form file
<form onsubmit="return CheckPassword(password)">
<div class="form-group">
<label class="password-text" for="password">Password</label><br>
<input id="password" type="password" placeholder="Password" name="password" required >
</div>
<button type="submit" class="form-button">Submit</button>
</form>

I'm having a cannot POST when attempting to submit a form with JS

I am having an issue with my Javascript and HTML where when I submit my form, I get a Cannot POST error. I already looked at Shows error "Cannot POST" when I try to submit the HTML form, but that seems to be server-based. I'm sorry, but I'm doing this for a class, so I'm in a bit of a time crunch right now.
My login JS code:
function login(){
var pw = document.forms['login']['passcode'].value;
var email = document.forms['login']["email"].value;
var login = userLogin().get();
if(email == "adrian#tissue.com" && pw == "welcome1"){
window.location = "issues.html";
}
else if(email == "admin#tissue.com" && pw == "admin123"){
window.location = "subscription-dashboard.html"
}
else if(email == login[0] && pw == login[1]){
window.location = "issues.html";
}
else{
alert("That password/email is incorrect");
return false;
};
}
My module for get is:
(function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
});
And my HTML code is:
<form action="#" name="login" method="post" onsubmit="return login()">
<input type="text" name="email" placeholder="Email" required>
<input type="password" name="passcode" placeholder = "Password" required>
<input type="submit" value="login">
</form>
Here's my fiddle for ease. I'm using Brackets and this class is Client side JS.
https://jsfiddle.net/MiguelPi/nmp6oxat/1/
Seems like you are trying to access to an anonymous function, rewrite userFunction like this (without external parentheses):
function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
}

how to send json data and 1-n files in POST body use javascript

I have from like this:
<form id="form" method='post' action="http://192.168.1.33/api/" enctype="multipart/form-data">
<label>User login: </label>
<input type="text" id="userLogin"><br />
<label>User password</label>
<input type="text" id="userPass"><br /><br />
<label>Input command here</label>
<input type="text" size="100" placeholder="users" id="command" name="command"><br/><br />
<input type="file" name="file1"><br/>
<input type="file" name="file2"><br/>
<br />
<input type="submit">
</form>
<h3>Output: </h3>
<div id="output"></div>
And simple javascript code. This code gets form data (attached files) and creating 2 fields in http header with userName and userPass, and send it to my api:
<script type="application/javascript">
var myCommand = document.querySelector('#command');
document.forms[0].onsubmit = function (event) {
if (window.FormData) {
event.preventDefault();
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var url = form.getAttribute('action') + '?' + myCommand.value;
xhr.open('post', url);
xhr.setRequestHeader('x-auth-user', document.querySelector('#userLogin').value);
xhr.setRequestHeader('x-auth-pass', document.querySelector('#userPass').value);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// server response: xhr.responseText
document.querySelector('#output').innerHTML = this.responseText;
}
};
xhr.send(data);
}
};
(function() {
document.querySelector('#userLogin').value = "user1";
document.querySelector('#userPass').value = "user";
})();
</script>
How can I add json data in body request use javascript? Json like this:
{
"id":"",
"status":0,
"documentName":"user",
"documentDesctiption":"",
"documentAttachedUsers":"id, id, id"
}
In fact I don't need form. I need to send 1-n files and one json string in POST body.
Now Api (php) receives just only form data (files). I plan on getting the body like this:
$inputJSON = file_get_contents('php://input');

Javascript to send form to PHP

I am trying to get my HTML form to pass through Javascript that will then pass it to PHP that will send it to MySQL.
However I either get the page to load the JS file in the browser, or the PHP file to load in the browser.
Here is my HTML form:
<div class="form" id="form" onclick="submitForm()">
<form id='contactform' action="js/contactform.js" method="post" onSubmit="submitForm()">
<input type="text" id="name" placeholder="Name" autofocus required><br>
<input type="text" id="email" placeholder="Email" required><br>
<input type="tel" id="telephone" placeholder="Telephone"><br>
Enquiry : <input type="radio" id="subject" value="enquiry" required>
Booking : <input type="radio" id="subject" value="booking" required><br>
<textarea id="message" required rows="20" cols="20" placeholder="Enter your message and I will try to get back to you within 2 days."></textarea><br>
<input type="submit" name="submit" value="Submit" class="submitbutton"/>
<input type="reset" name="clearbutton" value="Clear" class="clearbutton"/>
</form>
<div id="outcome"></div>
I want the outcome of the form submit placed into the "outcome" div
My JS code:
function getOutput() {
getRequest(
'php/getinfo.php',
drawOutput,
drawError
);
return false;
}
// handles drawing an error message
function drawError () {
var container = document.getElementById("content");
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById("content");
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
function submitForm(){
var name = document.getElementById('name').value;
var booking = document.getElementById('subject').value;
var enquiry = document.getElementById('subject').value;
var email = document.getElementById('email').value;
var telephone = document.getElementById('telephone').value;
var message = document.getElementById('message').value;
getRequest(
'php/form.php?' + params, //URL for the PHP file
procesOutput,
processError
);
return false;
}
function processOutput(){
var container = document.getElementById('outcome');
container.innerHTML = responseText;
}
function processError(){
alert("There has been an error, please try again");
}
and my PHP code:
$con=mysqli_connect("DBLocation","Username","Password",'DBName');
if (mysqli_connect_errno()){
die("Error: " . mysqli_connect_error());
}
$result = mysqli_query($con,"INSERT INTO `Contact`(`Name`, `Email`, `Telephone`, `Enquiry`, `Booking`, `Message`) VALUES ([value-2],[value-3],[value-4],[value-5],[value-6],[value-7])");
if ($conn->query($sql) === TRUE){
echo "Thank you for contacting us, I will replay to you soon!";
}
else {
echo "I'm sorry but an Error has occured. Please try again shortly";
}
mysql_close($conn);
?>
I've had a look at w3schools pages and some other questions on here but I can't seem to get my head around it.
A couple of things, first off what is getRequest? Second off, where is responseText defined? Third, I would check your console as I'm pretty sure there is an error in submitForm. I see lots of getElementByIds, but none of your inputs have ids associated with them:
<input type="text" name="name" placeholder="Name" autofocus required>
Should be:
<input type="text" id="name" placeholder="Name" autofocus required>
I believe you want to use Ajax, which you can easily use with jQuery.
I believe the answer for your question is right on this page: https://learn.jquery.com/ajax/ajax-and-forms/
If jQuery is new for you, you might want to read a little about jQuery: https://learn.jquery.com/about-jquery/
If you don't want to use jQuery, you can use directly XMLHttpRequest in javascript instead.
Here is a demo in JSFiddle.
Remove onClick, onSubmit, action="js/contactform.js" method="post" attributes as you don't need them. Capture the form submit in js. How to? - link
Add id's on the form elements so than you can select them like:
var name = document.getElementById('name').value;
Make a $.post request with jQuery (How to? - Link) and handle the success and failure callbacks. (I don't understand why are you making a post request, I would recommend you a $.get request.

JSONRequest.post not functioning

I am developing a web page and the purpose is to perform an http POST from form input elements, in JSON format. While the JSON element to be sent is formed properly, the request is never performed. Here is the code I have been using.
Form
<form id="input" action="javascript:snifForm()" >
User ID:
<input type="text" name="userId" id="userId" required>
Name:
<input type="text" name="name" id="name" required>
<div class="form-submit"><input type="submit" value="Submit" color="#ffffff" > </div></p>
</form>
Javascript (JSON.js, JSONRequest.js and JSONRequestError.js are imported)
<script type="text/javascript">
var requestNumber;
function snifForm()
{
var a1=document.getElementById("userId").value;
var a2=document.getElementById("name").value;
var toSend= {interactions: {id_user:a1, id_name:a2}};
var jToSend=JSON.stringify(toSend);
requestNumber = JSONRequest.post(
"http://someurl.com",
jToSend,
function (requestNumber, value, exception) {
if (value) {
processResponse(value);
alert(value);
} else {
processError(exception);
}
}
);
alert(requestNumber);
}
</script>
I also tried the more classic form:
var xmlhttp = new XMLHttpRequest();
var out;
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
out = xmlhttp.responseText;
alert(out);
}
else alert('nothing');
}
xmlhttp.open("POST", "the_same_url", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(jToSend);
After checking the server logs, no post is done ever :/
You should be attaching the event to the submit action of the form and you need to make sure to cancel the submit action.
I would not add the events directly to the form, but it is
<form id="input" onsubmit="snifForm(); return false;">

Categories