I've got 2 HTML input textbox: "Email" and "Password". Whenever I submit these textboxes with no value I get this SQL exception: SqlException: The parameterized query '(#email nvarchar(4000),#password nvarchar(4000))SELECT Email,Pas' expects the parameter '#email', which was not supplied.
I just want an message that says that I need to fill in a email and password. I've already an JS function that checks these textboxes for empty value and it works. But it still redirects to the SQL Exception page afterwards. I think I've done something stupid with my database properties. How can I fix this?
string sqlquery = "SELECT Email,Password FROM [dbo].[User] WHERE Email = #email and Password = #password;";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#email", user.Email);
sqlcomm.Parameters.AddWithValue("#password", user.Password);
SqlDataReader sdr = sqlcomm.ExecuteReader();
if (sdr.Read())
{
return RedirectToAction("Index", "Home");
}
else
{
ViewData["Message"] = "Fout";
}
sqlconn.Close();
return View();
Login
<form asp-action="Login" method="post">
<input id="loginEmail" type="text" name="Email" asp-for="#Model.Email" />
<input id="loginWachtwoord" type="password" name="Password" asp-for="#Model.Password" />
<input type="submit" onclick="CheckNullOrEmpty()" value="Login" />
<h1>#Html.ViewData["Message"]</h1>
</form>
just check the parameters before you try to query the database
if(string.IsNullOrEmpty(user.Email) || string.IsNullOrEmpty(user.Password)) {
ViewData["Message"] = "Fout";
return View();
}
//... validate first then try to create the statement.
You could also try/catch the errors and return the View in the catch block if you don't want the error page popping up. There's also ModelState.IsValid which you can read about
Related
I am trying got take the value that is inserted into the first and last name fields and then take that and insert it into a MySQL database backend that I have running using restAPI. I got some help to fix the form but I am trying to find the error when I try to take the input form the form and enter it in the database
The table code is this
<div class="superhero">
<h1>Lets add our first name </h1>
<form action="/add_user" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<form action="/add_user" method="post">
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
Then this is taken into the nodeJS server with this command
app.post('/add_people', function(req, res){
axios.get('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
Then at the end it is going to be taken to the RestAPI with that is using this route
#app.route('/api/adduser', methods = ['POST']) # This is a post method because the user needs to be able to add info
def adding_stuff():
request_data = request.get_json() # Gets the info from the table and converts to JSON format
new_fname = request_data['firstname']
new_lname = request_data['lastname']
conn = create_connection("", "", "", "")
sql = "INSERT INTO restaurantusers (firstname, lastname) VALUES ('%s', '%s');" % (new_fname, new_lname) # This sql statement will then be uploaded to the databse to add a new record
execute_query(conn, sql) # This will execute the query
return 'Post worked'
Sorry if what I am asking sounds really complicated. Professor goes too fast in class and I've been trying to find out how to do this for sometime with no luck.
UDATE: I later changed the two items as suggested. The route is
app.post('/add_people', function(req, res){
axios.post('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
and the form is now
<form action="/add_people" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
I get the error that
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
and also this error on the restAPI window
TypeError: 'NoneType' object is not subscriptable
First, you'll need to update your form and inputs to accept user input properly by using the value attribute on the <input> so instead of
<input type = "text" firstname = "firstname">
<input type = "text" lastname = "lastname">
Do this
<input type="text" value="firstname">
<input type="text" value="lastname">
this will send the values firstname and lastname to your API.
If you need to dynamically accept user input you'll need to watch input changes using javascript and handle the form submit with it too. Check
input value attribute and Javascript form.
To send the data from your node server to your python server you'll need to update
axios.post('http://127.0.0.1:5000/api/adduser')
To
axios.post('http://127.0.0.1:5000/api/adduser', { first_name: req.body.firstname, last_name: req.body.last_name })
Because that way you're passing the form data inside req.body to your python server
So, im trying to create a accounts system, i made a login system that works, but when you enter wrong credentials i want it to display "wrong username or password" in the value of ab empty tag, the thing is that i dont know how to access the tag from app.js (node.js project)
<div class="form">
<form class="login-form" action="/account" method="post">
<p id = "check"></p>
<h1 id = "login-text">Login</h1>
<label style="color:white;">Username:</label>
<input type="text" id = "username" placeholder="Enter Username" name="username" required>
<label style="color:white;">Password:</label>
<input type="password" id = "password" placeholder="Enter Password" name="password" required>
<button type="submit">Login</button>
<h5>register</h5>
</form>
</div>
</div>
app.post('/account', (req, res) => {
const username = req.body.username;
const password = req.body.password;
con.query("USE discbin")
con.query('SELECT * FROM accounts WHERE username = ?', [username], function (err, result, fields) {
if (err) throw err;
if (result.length > 0 && result[0].password === password) {
console.log(result[0].username + " logged in!")
res.render('account');
}
else {
console.log("a user tried to login using the username: " + username)
//set <p> to "wrong username or password"
}
});
});
document.getElementById("check").textContent = "wrong username or password";
Get the element you want to update document.getElementById("check")
Set its textContent property to the text you want to use
I think this is an XY problem.
As far as I know, it is not possible to access a DOM element directly from the server, however, you can achieve the same result with a little JavaScript on the client side.
For example the server response could be on authentication success a JSON object like that:
{
auth: true,
//some token I guess...
}
and on authentication fail:
{ auth: false }
Then, you can use JavaScript to access the element you want and modify its content using the innerHTML method.
In your case, you could store the string to be displayed and modify it according to the server response.
let checkStringVariable = "";
On server response:
checkStringVariable = response.auth ? "" : "wrong username or password";
document.getElementbById("check").innerHTML = checkStringVariable;
Good Evening,
I am trying to create a simple JavaScript login form that will validate by checking only 1 specific email address which has been declared and 1 password that has been declared.
However, no matter what is typed into the fields, even if nothing is present, once the submit button is clicked, the user is directed to the desired page.
I need it to only allow the desired page if the email address and password are the correct. Otherwise, notify them that it is incorrect.
Here is a link to [codepen][1] so you can see the page and script.
https://codepen.io/m0rrisim0/pen/bmzyqj
Any help is appreciated in figuring out why the script is not validating.
You have to use the attribute value from document.getElementById method,
like the following example: document.getElementById("UserName").value
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
if ((UserName == email) && (Password == pass)) {
return true;
} else {
alert("UserName and/or Password Do Not Match");
return false;
}
}
Your form's inputs lack the id atrribute and should return the function on submit event.
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
UserName:
<input type="text" name="UserName" id="UserName">
<br>
<br>
Password:
<input type="password" name="Password" id="Password">
<hr>
<input type="submit" value="Submit">
</form>
Your problem was getElementById(), this function requires a argument and cause a error. Because of this error the line loginform.onsubmit = validate; was never reached so the submit button submit the form without calling a validate function.
There is no need to put this line inside the if statement, but if you want you can change a little bit to getElementById without the parentesis, this way it evaluates to a function that in js is truthy.
You can check a working version of you code here:
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
https://codepen.io/francispires/pen/mzvYKX
You can improve this validation
I have a simple Window Forms application that opens up a webpage with set parameters.
The link send the user to a page with 2 text box fields and a submit button.
I am trying to automate this process so it grabs the parameter values and puts it into the text box then clicks submit .
This is my current code for my windows form:
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
libLink.Links.Remove(libLink.Links[0]);
libLink.Links.Add(0, libLink.Text.Length,
"http://www.example.com/?UserName=value1&FirstName=value2");
}
private void libLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
ProcessStartInfo sInfo = new ProcessStartInfo(e.Link.LinkData.ToString());
Process.Start(sInfo);
}
}
}
How can I create a script that that takes those parameters in the URL to populate two text box fields and then submit the form?
This is my HTML Page:
<form action="/send" method="post" novalidate="novalidate">
<input class="form-control" data-val="true" data-val-UserName="Wrong username" data-val-required="Enter a valid Username" id="Username" name="Username" placeholder="Username" type="text" value="">
<input class="form-control" id="FirstName" name="FirstName" placeholder="First Name" type="text" value="">
<button type="submit">Sign In</button>
</form>
Fairly new to coding so I tried to keep my code as simple as possible.
I looked at possible methods such as QueryStrings, JavaScript and Jquery, but I am not sure how to approach this problem.
There's a few ways of doing it really but i'll give you a basic walk through of how i would do it in javascript with a bit of JQuery.
we have variable with the URL we start by:
var url = "http://www.example.com/?UserName=value1&FirstName=value2"
var params_string = url.split("?")[1] //UserName=value1&FirstName=value2
so first we split the string into a list like above which returns a list of the items which are separated by the "?" character, but we only need the second item(at index 1) so we add the [1] to the end to only store that bit.
We then split this again to get the individual parameters.
var params_string_list = params_string.split("&")
["UserName=value1","FirstName=value2"]
which returns a list as above, again need to break that down i would make it into an object like so :
var params = {}
for(var i =0;i < params_string_list.length;i++ ){
var temp = params_string_list[i].split("=") // looks like ["UserName","value1"]
params[temp[0]]= temp[1]
} //params now looks like {"UserName":"value1","FirstName":"value2"}
as this makes it easy to access and use.
we can then do the following to set the values in the form:
if(params.UserName){
$('#Username').val( param.UserName );
}
if(params.FirstName){
$('#FirstName').val( param.FirstName );
}
if statments are there to check that the value exists in the object so we don't sent the value to "undefined" by accident.
Hope this helps.
I am using Angular-Payments that intercepts the form data and submits it to Stripe. This works well, however, I'm not sure how to access form data after its sent to stripe. For example, my form has quantity field which I would like to get access to but I don't know how to...
Here is what I'm doing HTML
<form stripe-form="handleStripe" role="form" ng-if="authenticated" name="takeMoneyForm" ng-submit="takeMoney(takeMoneyForm, model)">
<input type="text" name="card_number" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="takeMoneyForm.number.$card.type">
<input type="text" name="card_cvc" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type">
<input type="text" nam="card_expiry" ng-model="expiry" payments-validate="expiry" payments-format="expiry">
<input type="text" ng-model="quantity"/>
<button class='form-control submit-button btn btn-majoo' type='submit'>Pay ยป</button>
</form>
JS
$scope.takeMoney = function(formData, model){
$scope.handleStripe = function(status, response){
if(response.error) {
// there was an error. Fix it.
alert("Error happened")
} else {
var dataModel = {
email: model.email,
profile: {
stripe_token: response.id,
stripe_id: model.profile.stripe_id
//here I would like to get access to the quantity from the form
}
}
djangoAuth.takeMoney(dataModel)
$scope.complete = true;
}
}
}
I feel like this should be simple but I'm very new to Angular and can't seem to figure this out.
since youre using ng-model the values of those fields should be on that form's scope(as in scope.number)
If they are not accessible it could be one of two things:
1) Angular Payments clears the ng-model following submit
2) you are trying to access it from a different scope.