Adding User to list after email validation - javascript

Tried this a few times but can not get user to add to list after validation
Instructions
PURE JAVASCRIPT
Dynamically add a user to the users list.
Highlight the email input when a user enters an invalid email address and display following message: "please enter a valid email address" in red.
Use the addUser function to submit the user's data.
If the ajax request returns an error, display the error message in red.
Display the newly added user in the users list when the request was successful.
html
<form id = "myForm">
<h2>Add a User:</h2>
<input type="text" name="username" placeholder="name">
<input type="email" name="email" placeholder="email">
<button>add user</button>
<h2>Users:</h2>
<ul id="users"></ul>
Function
// Do not modify this function. Add user service wrapper.
function addUser(username, email, callback) {
var xhr = new XMLHttpRequest();
var response;
var success = (!!Math.round(Math.random()));
if (!success){
response = JSON.stringify({
success: success,
error: "Oups, something went wrong!"
});
} else {
response = JSON.stringify({
success: success,
user: {
username: username,
email: email
}
});
}
xhr.open("POST", "/echo/json/");
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
}
}
xhr.send("json=" + response);
};
jsfiddle http://jsfiddle.net/17e59p4w/2/
My code works as far as email validation but I don't understand how to addUser using the given function

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>

Page isn't working error, Node js freezes

I'm using Node for the first time and am having trouble when a certain response is triggered. In this case, I'm checking if the username and pw matches what I have in DynamoDB. It redirects to my page when the username and pw don't match my db, but when it does, all of my console.log output prints twice (which apparently has something to do with the favicon in Chrome) like "online" and "[pw] + database.js," but it also freezes my IDE and terminal. I then see the "The page isn't working, localhost didn't send any data" error in my browser. Ignore the privacy problems :) Thoughts?
database.js:
var myDB_lookup = function(username, password, route_callbck){
console.log('Looking up: ' + username);
users.get(username, function (err, data) {
if (err) {
route_callbck(null, "Lookup error: "+err);
} else if (data == null) {
route_callbck(null, null);
} else {
// JSON object that stores password & fullname
var value = JSON.parse(data[0].value);
var pw = value.password;
if (pw.valueOf() == password.valueOf()){
route_callbck({ password : pw }, null);
console.log(pw + "database.js");
}else{
//console.log('wrong password');
route_callbck(null, null);
}
}
});
};
routes.js:
var checkLogin = function(req,res){
var user = req.body.username;
var pw = req.body.password;
console.log(user + pw + "routes");
db.lookup(user, pw, function(data, err) {
if (data!=null){
console.log("online");
//req.session.username = user;
//req.session.password = pw;
}else{
res.render('main.ejs',{error:"Fields incorrect"});
}
});
};
main.ejs:
<form method="post" action="/checklogin">
Enter username here: <br>
<input type="text" name="username" placeholder = "Your username"> <br>
Enter password here: <br>
<input type="password" name="password" placeholder = "Your password">
<input type="submit" value="Log In">
</form>
The functions are all linked up in routes.js when I do module.exports = ...
You probably forget to send the response, make sure
res.render() or res.json() or res.send() gets hit
you should put a try/catch around JSON.parse(), that's a best practice.
Looks like your culprit is here:
if (data!=null){
console.log("online");
//req.session.username = user;
//req.session.password = pw;
// you need to send the response here too! <<<<<
res.render('main.ejs'); //// !!!
}else{
res.render('main.ejs',{error:"Fields incorrect"});
}

XHR doesn't get the proper status code

Here is a server-side function that receives a POST request and handles its response. As you can see, when no error occurs, the status code of the response is 200.
app.post('/submit', function(req, res) {
var p = new Promise(function(resolve, reject) {
db.serialize(function() {
db.run("INSERT INTO users VALUES (?, ?, ?, ?)",
[req.query['email'], req.query['company'], req.query['subject'], req.query['text']],
function (err) {
if (err) {
console.error(err);
reject();
} else {
console.log("Transaction passed");
resolve();
}
});
});
});
p.then(function(){
res.status(200).end();
}).catch(function() {
res.status(400).end();
})
});
In the client side, I wrote a JS function that sends an AJAX POST request to the server and handles the response:
function addFormToDB(email, company, subject, text) {
var xhttp = new XMLHttpRequest();
var params = "email=" + email + "&company=" + company + "&subject=" + subject + "&text=" + text;
xhttp.open("POST", "http://127.0.0.1:3000/submit?" + params, true);
xhttp.onreadystatechange = function() {
console.log(xhttp.readyState + " " + xhttp.status);
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log("request " + params + " was sent to DB");
alert("Thank You!");
}
};
xhttp.send();
}
When I invoke the function 'addFormToDB' from the console window of the browser, it sends an AJAX request to the server and gets it back with an xhhr.status of 200.
However, 'addFormToDB' has to be invoked when the user fills a form and clicks the 'submit' button. When this happens, the xhhr.status sent back from the server to the browser is always 0. I don't know why.
Here is the HTML code that creates the form:
<form id="form">
<label for="email"> E-mail: </label>
<input id = "email"> <br>
<label for="company"> Company: </label>
<input id = "company"> <br>
<label for="subject"> Subject: </label>
<input id = "subject"> <br>
<label for="text"> Text: </label>
<input id = "text"> <br>
<input type="submit" value="Submit" id="button"><br><br>
</form>
...
<script>
$("#form").submit(function() {
addFormToDB($("#email").val(), $("#company").val(), $("#subject").val(), $("#text").val())
});
</script>
Can you help me find out the bug?
The immediate issue is that you don't prevent the default action of a form submit - which is to POST data to the server and reload the page. As a side-effect this cancels all running Ajax requests, which causes the effect you see.
To prevent the default event action, call preventDefault() on the event object.
function submitHandler(e) {
e.preventDefault();
// some processing, for example Ajax
// the browser will not issue a traditional POST request
}
Back in the day, return false; had the same effect, but nowadays.preventDefault() is the way to go.
Further comments on your code:
Client Side
Don't roll your own Ajax functions. Ajax libraries are plenty and convenient, well-tested and provide easy-to-read Ajax support that prevents common errors and does all kinds of heavy lifting transparently. Just use one of the many libraries.
With jQuery, which you seem to be using anyway, the function becomes as straight-forward as this:
function addFormToDB(email, company, subject, text) {
return $.post("http://127.0.0.1:3000/submit", {
email: email,
company: company,
subject: subject,
text: text
})
.done(function (data) {
console.log("received", data);
alert("Thank You!");
})
.fail(function (jqXhr, status, err) {
console.error(err);
});
}
Server Side
Don't do your own promisification. It might look easy enough, but just as with Ajax, there's enough stuff that can go wrong and is easily overlooked. Let a library do it for you, or use a wrapper library that did it for you. For node-sqlite3, one such wrapper library exists: co-sqlite3. I recommend you look at it.
Your code could look like this:
app.post('/submit', function(req, res) {
var q = req.query;
var params = [q.email, q.company, q.subject, q.text];
db.serialize()
.then(() => db.run("INSERT INTO users VALUES (?, ?, ?, ?)", params))
.then(() => res.status(200).end())
.catch((err) => {
console.error(err);
res.status(400).end();
});
});
});
Or use one of the async/yield variants shown in the library's samples.

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.

How to receive POST form data in node.js from client

Hello guys i am a newbie when it comes with web development, especially working with node.js, i want to find out how i can receive data sent from client via ajax Post.
below is the script i wrote to post the form data
<script type="text/javascript">
function ecoachSignIn(){
var user = $('#user').val();
var password = $('#pass').val();
var SignIn ={
user : $('#user').val();
pass : $('#pass').val();
};
$.ajax({
type:'POST',
url: 'https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user='+username+'&pass='+password,
data: {
user : $('#user').val();
pass : $('#pass').val();
},
success: function(creditials){
}
});
alert("Hello! your username is "+username+" and password is "+password);
}
this is the form itself
<form style="margin-top:25%; margin-left:30%" method="post" action='/'>
<input class="input" type="text" id="user" required="true" name="username" placeholder="Username">
<input class="button-1" style="background:#000" onClick="ecoachSignIn()" type="submit" value="Log in">
<div style="margin-top:10px">
<input class="input" type="password" id="pass" name="password" required="true" placeholder="Password">
</div>
</form>
node.js server code
router.post('/', function(req, res) {
var request = require("request"),
user_name=req.body.username,//this picks the username frome the form directly not from the javascript i created to post the data
password=req.body.password,//same problem with the username
url = req.query.url;//trying to get the url in my jQuery at client side but not working
console.log("Username = "+user_name+", password is "+password);
request.get(
{
url : url
},
function (error, response, body) {
// Do more stuff with 'body' here
if (!error && response.statusCode == 200) {
var json_body = JSON.parse(body);
console.log(json_body);
status = json_body.status;
success = json_body.msg;
fname = json_body.profile.fname;
console.log("hi "+fname); // Print the username.
console.log("status is "+status); // Print the status.
console.log("success is "+success); // Print the success.
}
}
);
res.end("yes");
});
My major problem is how to process this in node.js backend server
Hope my question is clear ....thanks
Your server side code:
user_name=req.body.username,//this picks the username frome the form directly not from the javascript i created to post the data
password=req.body.password,//same problem with the username
Your client side code:
user : $('#user').val();
pass : $('#pass').val();
You call the fields user and pass on the client but username and password on the server. You have to use the same name in both places.
It works when you use the form normally because the name attributes match the names you use the on server.

Categories