I almost always work with python so all this is new-ish to me. Here I am in the early stage of building a web app with a simple login page. I am trying to make it so that when I click the login button, the onclick action in the html should call the login_user function to make a rest request to the backend api I already built.
Heres the html and js function:
<div>
<label for="username">username:</label>
<input type="text" id="username" name="username">
</div>
<div>
<label for="password">password:</label>
<input type="password" id="password" name="password">
</div>
<button id="loginButton" onclick="login_user()">login</button>
<script type="text/javascript">
function login_user(path, username, password) {
'http://127.0.0.1:5000/' = path;
document.getElementById('username') = username;
document.getElementById('password') = password;
let data = {username: username, password: password};
return fetch(path, {method: "GET", body:
JSON.stringify(data)});
};
</script>
However, this won't make a request. I dont think the issue is within the javascript? I've tried to make a more simpler function that would simply redirect me to the homepage at the onclick but that wouldnt work either. I am not too sure what is going on and if you could point me in the right direction that would be amazing!
function login_user(path, username, password) {
'http://127.0.0.1:5000/' = path; // Assigning values is wrong.
...
}
You have to rewrite the function as:
function login_user() {
let path = 'http://127.0.0.1:5000/';
let username = document.getElementById('username');
let password = document.getElementById('password');
let data = {username: username, password: password};
return fetch(path, {method: "GET", body:
JSON.stringify(data)});
};
Is syntax error !
'http://127.0.0.1:5000/' = path;
Login function, for security, you should use POST method.
See more about fetch api: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Try this, it seems you are getting undefined for the input values
function login_user(path, username, password) {
path = 'http://127.0.0.1:5000/';
username = document.getElementById('username').value;
password = document.getElementById('password').value;
let data = {username: username, password: password};
return fetch(path, {
method: "GET",
body: JSON.stringify(data)
});
};
<body>
<div>
<label for="username">username:</label>
<input type="text" id="username" name="username">
</div>
<div>
<label for="password">password:</label>
<input type="password" id="password" name="password" minlength="8" required>
</div>
<button id="loginButton" onclick="login_user()">login</button>
<script type="text/javascript">
function login_user() {
let path = "http://127.0.0.1:5000/api/resource";
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let data = {username: username, password: password};
fetch(path, {
headers: {
"Content-Type": "application/json"},
method: "POST",
body: JSON.stringify(data)}
);
fetch("http://127.0.0.1:5000/");
};
</script>
Related
$(document).ready(function() {
$("#loginForm").on('submit', function() {
var mail = document.getElementById("mail").value;
var password = document.getElementById("password").value;
req = $.ajax({
url: '/api/login',
type: 'POST',
data: {
email: email,
password: password
}
});
req.done(function(data) {
if (data.result == "failed") {
let messageHandler = document.getElementById("message-handler");
messageHandler.innerHTML = `<h3> username or password incorrect </h3>`;
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST">
<input type="mail" id="mail" name="mail">
<input type="text" id="password" name="password">
<input type="submit" id="loginForm">
</form>
<div id="message-handler">
</div>
When I click the button, it simply says Method not allowed because I am sending a post request from form. The js never detects the on submit event.
Thanks
What happens here in /api/login? Try to point a file like form.php or something else.
req = $.ajax({
**url: '/api/login',**
type: 'POST',
data: {
email: email,
password: password
}
});
Maybe this is the path you need to follow for your answer ;)
Use action='url' Or action='#' this will help to detect your request in browser.
First, I read somewhere that we should not use XMLHttpRequest.
Second, I am a newbie in Javascript.
Third, I created a webpage to submit email and password.
<form method="POST" onsubmit="return check();">{% csrf_token %}
<p><b>Login</b></p>
<input type="email" name="email" placeholder="Email" required></input>
<input type="password" name="password" placeholder="Password" id='new_password' ></input>
<span id='message'>{{msg}}</span>
<button type="submit" onclick="check()" name="Submit"><b>Submit</b></button>
</form>
My check function is
function check() {
document.getElementById('message').innerHTML = "checking";
const url = "https://<hostname/login";
const data = {
'email' : document.getElementById('email').value,
'password' : document.getElementById('password').value
};
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8" },
body : data,
method : "POST",
mode : "cors"
};
fetch(url, other_params)
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error("Could not reach the API: " + response.statusText);
}
}).then(function(data) {
document.getElementById("message").innerHTML = data.encoded;
}).catch(function(error) {
document.getElementById("message").innerHTML = error.message;
});
return true;
}
This code is not working and just redirects me to the same page again and again.
Please help me understand what am I doing wrong.
The problem with your code is that you are not "intercepting" the submit event of your form so it will execute the default behavior which is POST to itself (since it doesn't have an instruction that tells it where to go). Unless you can have a chance to stop this default behavior, the form will perform this action.
To intercept the form's submit event you have to tell the browser to watch out of this event and execute a custom function instead of using an event listener like below:
<script>
document.getElementById('whatever-form-id')
.addEventListener('submit', check);
function check(e) {
e.preventDefault();
// and now anything else you want to do.
}
</script>
This will prevent your form from posting and it will execute your function instead.
There were some errors in your code as I've checked, please use it like this
<form method="POST" onsubmit="return check();">{% csrf_token %}
<p><b>Login</b></p>
<input type="email" id = "email" name="email" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" id='new_password' >
<span id='message'>{{msg}}</span>
<button type="submit" onclick="check(event)" name="Submit"><b>Submit</b> </button>
</form>
<script>
function check(event) {
event.preventDefault();
document.getElementById('message').innerHTML = "checking";
const url = "https://hostname/login";
const data = {"email" : document.getElementById('email').value,
'password' : document.getElementById('new_password').value
};
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8"},
body : data,
method : "POST",
mode : "cors"
};
fetch(url, other_params)
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error("Could not reach the API: " + response.statusText);
}
}).then(function(data) {
document.getElementById("message").innerHTML = data.encoded;
}).catch(function(error) {
document.getElementById("message").innerHTML = error.message;
});
return true;
}
</script>
Then test by changing your post URL to correct one whether working or not, for more testing use browser inspector tool to see your ajax request.
I've also put it on fiddle for your live testing http://jsfiddle.net/rajender07/xpvt214o/903616/
Thanks
1) Your validation function always returns true
2) When you use fetch..then, its promises can be executed later than return statement
So your form will be refresh again and again. You should return false, and manually submit the form with JavaScript when you get an onSuccess response.
<script>
function check(event) {
document.getElementById('message').innerHTML = "checking";
const url = "https://localhost:8080/login";
const data = {
'email' : document.getElementById('email').value,
'password' : document.getElementById('new_password').value
};
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8" },
body : data,
method : "POST",
mode : "cors"
};
fetch(url, other_params)
.then(function(response) {
if (response.ok) {
alert(response.json());
} else {
throw new Error("Could not reach the API: " + response.statusText);
}
}).then(function(data) {
document.getElementById("message").innerHTML = data.encoded;
}).catch(function(error) {
document.getElementById("message").innerHTML = error.message;
});
return false;
}
</script>
<form method="POST" onsubmit="return check();">{% csrf_token %}
<p><b>Login</b></p>
<input type="email" id = "email" name="email" placeholder="Email" required></input>
<input type="password" name="password" placeholder="Password" id='new_password' ></input>
<span id='message'>{{msg}}</span>
<button type="submit" name="Submit"><b>Submit</b></button>
</form>
Update:
Page not refreshed, error message displayed:
Firstly, I would like to understand what is your object after getting the data from REST API.
Secondly, there are mistakes in the html code as well, you don't need to add onclick on the submit button when there you already have a onsubmit on the form element.
Solution,
change
onsubmit="check(event);"
function check(e) { e.preventDefault() ... } // you can remove the return true
just going off the top of my head here but you've set the Content-Type to application/json in the headers but your body is not an JSON string
try making your body match the headers by doing
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8"},
body : JSON.stringify(data),
method : "POST",
mode : "cors"
};
EDIT
So after re-reading your question, I think what is happening is you've set your button to type of submit and what is happening is when you click on the button, your form is getting posted through the good old form post and your page gets refreshed from the postback.
If you want to handle form posts yourself using fetch, change your button type to button and the form should no longer actually post then everything else will be handled by your click event handler.
ps. while you're at it, you can remove the method and onsubmit attribute from your form tag as well
So your form should look something like this
<form>
<p><b>Login</b></p>
<input type="email" name="email" placeholder="Email" required></input>
<input type="password" name="password" placeholder="Password" id='new_password' ></input>
<span id='message'>{{msg}}</span>
<button type="button" onclick="check()" name="Submit"><b>Submit</b></button>
</form>
I am trying to build an angularjs program which talks to express / nodejs api and mysql database.
In login page , I am able to call the api correctly and it connects with mysql and based on right combination of user name and password , I am sending back "password matches" or "failure".
When I am accessing that on HTML using $scope , I am getting ["password matches"] and not password matches . I have tried toString, splice, etc but no proper result.
Controller
var passStats=[];
passStats = LoginFactory.validateUserLoginFactory(uName, pWD)
$scope.pwdStatus = passStats;
Factory
app.factory("LoginFactory", function ($http) {
var factory = {};
factory.validateUserLoginFactory = function (UserName, PWD) {
$http({ method: "POST", url: 'http://localhost:3000/validateUserLogin/', data: { limit: userForm }, cache: false }).then(function (response) {
StatusPWD.push(response.data);
}, function (error) { console.log(error); });
return StatusPWD;
}
return factory;
});
node.js
res.send('password matches');
HTML
<label>User Name</label>
<input type="text" ng-model="enteredUserName" class="w3-input w3-border w3-padding">
<br>
<label>Password</label>
<input type="text" ng-model="enteredPWD" class="w3-input w3-border w3-padding">
<br>
<input type="button" ng-Click="validateLogin(enteredUserName,enteredPWD)" value="Login" class="w3-btn w3-padding w3-green">
<br> <br> <br>
<label>password {{ pwdStatus}}</label>
It is because you are using StatusPWD.push which is pushing it into an array.
the passStats variable is an array, where you are pushing the response.
you can simply do this to get the value if passStats is an array
$scope.pwdStatus = passStats[0]
or you can do
$scope.pwdStatus = passStats.join("")
I have solved my problem for which I posted the question. I had coded the factory and controller part wrongly. Following modification is giving me proper out put in HTML
Factory
factory.validateUserLoginFactory = function (UserName, PWD) {
var userForm = {};
userForm = { user: UserName, password: PWD };
return $http({ method: "POST", url: 'http://localhost:3000/validateUserLogin/', data: { limit: userForm }, cache: false });
}
Controller
$scope.pwdStatus;
LoginFactory.validateUserLoginFactory(uName, pWD)
.then(function (data) {
console.log(data.data);
$scope.pwdStatus = data.data;
}, function (data) {
console.log(data);
});
I am new using Angularjs and I am having an issue while parsing a JSON response. I am doing client side authentication for the login page and I have used get request to fetch data from servers side and post request for client side.
HTML code :
<form ng-submit="loginform(logcred)" class="ng-scope ng-pristine ng-valid center" name="logform"><br/><br>
<tr ng-repeat="logcred in serverinfo"></tr>
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username" >
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="submit()">Login</button>
</div>
<br/>
</form>
AngularJS code :
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
/* server side response*/
$http.get('http://localhost:3000/loginfo
.then(
function successCallback(response){
$scope.serverinfo = response.data;
});
/* client-side response*/
$scope.loginform = function(serverinfo,username,password){
$http({
url: 'http://localhost:3000/loginfo',
method: 'POST',
data: {
"username" :username,
"password" :password,
}
})
.then(
function successCallback(response){
console.log(response);
if (serverinfo.username === response.data.username && serverinfo.password === response.data.password) {
$scope.signinfo = response.data;
}else{
console.log("Error: " + response)
}
});
}
Problem what I am facing is, I need to send the GET response data into POST request and there I am doing the condition check, if the username and password matches, it's should give success meassage. But I am not sure my thinking is right or not.
What am I doing wrong?
Any help / advice would be greatly appreciated.
You can try below code.
$scope.loginform = function(serverinfo,username,password){
$http({
url: 'http://localhost:3000/loginfo',
method: 'POST',
data: {
"username" :username,
"password" :password,
}
})
.then(
function successCallback(response){
console.log(response);
if (response) { // Response will be either true or false. For this yu need to change the API response.
//Logged in successfully
}else{
//Something went wrong
}
});
}
I'm trying to POST a form using C#
I make some searches, however I couldn't code it right way (I am new in this field).
Here are my codes;
View;
<form>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" id="input-username" name="Username" required autocomplete="on" />
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" id="input-password" name="Password" required autocomplete="on"/>
</div>
<p class="forgot">Forgot Password?</p>
<button class="button button-block" id="button-login">Log In</button>
</form>
Controller;
// GET: User
[HttpPost]
public ActionResult Login()
{
string username = Session["Username"].ToString();
string password = Session["Password"].ToString();
Service iLocationService = new Service();
var result = Service.MemberGetLogin( username, password, "127.0.0.1" );
ViewBag.Message = result;
return View();
}
Javascript;
jQuery(document).ready(function () {
$("#button-login").click(function () {
$.ajax({
type: "POST",
url: "/Controllers/UserController/login/",
data: $(this).serialize(),
dataType: "json"
})
.done(function (result) {
console.log(result);
})
.fail(function (a) {
console.log( a);
});
});
});
What I am trying to do is POST the input values to chech the user.
Thanks in Advance
Look at this line
string username = Session["Username"].ToString();
In your code you are trying to read the username and password values from Session variables. Who set the user name and password to Session ? You should be reading those from the posted form and use that.
[HttpPost]
public ActionResult Login(string userName,string password)
{
// do something with userName and password and return something
}
Also, you need to make sure that you are serializing the form, not the button clicked. I personally prefer to use the Html helper method to generate the form tag and use the action attribute value of the form in my javascript code instead of hardcoding the urls.
So in my razor view
#using(Html.BeginForm("login","User"))
{
//Your existing form inputs goes here
<button class="button button-block" id="button-login">Log In</button>
}
and in the script
$("#button-login").click(function () {
$.ajax({
type: "POST",
url: $(this).closest("form").attr("action"),
data: $(this).closest("form").serialize()
})
});
Since you are doing an ajax form submit, i suggest you return a json response which your client code can parse and do further things.
[HttpPost]
public ActionResult Login(string userName,string password)
{
//if userName and password are valid
return Json(new { Status="success"});
// else
return Json(new { Status="failed", Message="Invalid credentials});
}
and in your done callback, you should inspect this value and do further things
.done(function (result) {
if(result.Status==="success")
{
window.location.href="/Home/Index"; // change to wherever you want to redirect to
}
else
{
alert(result.Message);
}
})