email validation and email exists check using ko.observable - javascript

i want to apply validations on email if email is valid or not , and after that check in db using ajax to verify email already exist and email already exixt check should work if first check is passed , here is what i did , iam stucked in email_already_exist check that how to validate only if above check is passed , if anyone have idea how to do that
// code which checking email is valid
email: ko.observable((ref = REGISTRY.unsavedUser) != null ? ref.email : void 0).extend({
required: true,
email: {
params: true,
message: 'Please enter a valid email.'
},
focus:true
}),
// function to check email exists
var email_exist_check = function() {
var errorElement = $('#parent-email-signup');
var emzil = errorElement.val();
return = $.ajax({
url: '/api/v3/email_exists',
method: 'POST',
async: false,
data: {
email: emzil
},
success: function(data){
console.log(data);
},
error: function (response, status) {
showFlashMessage('An error occured, please try again later.', 'error');
}
});
};
email exist function is ready iam stucked that how to use in the above code
please help

Never, never never use async: false on Ajax calls.
What you need:
An API wrapper, for convenience and code readability later.
const API = {
email_exists: function (email) {
return $.post('/api/v3/email_exists', {
email: email
}).then(function (result) {
// evaluate result & return true (email exists) or false (email is free)
return ...;
}).fail(function (jqXhr, status, error) {
showFlashMessage('An error occured, please try again later.', 'error');
console.log('Error in email_exists', email, jqXhr, status, error);
});
},
// add other API functions in the same way
};
and async validation rule that calls your API:
ko.validation.rules.emailFromAPI = {
async: true,
validator: function (val, params, callback) {
API.email_exists(val).done(function (exists) {
callback(!exists); // validation is successful when the email does not exist
});
},
message: 'Please enter a valid email.'
};
an observable that uses this rule:
email: ko.observable((ref = REGISTRY.unsavedUser) != null ? ref.email : void 0).extend({
required: true,
emailFromAPI: true,
focus:true
}),

Since ajax is asynchronous you'll have to wait for the server response, returning the ajax call will not wait for the server call to resolve. One way to solve this is using a callback (another would be promises with async/await)
var email_exist_check = function(email, onSuccess, onError) {
$.ajax({
url: '/api/v3/email_exists',
method: 'POST',
async: false,
data: { email },
success: function(data){
console.log(data);
if (data && !data.error) { return onSuccess(); }
return onError(data && data.error);
},
error: function (response, status) {
onError(response);
}
});
};
// After doing a front-end email verification
email_exist_check(ref.email, () => {
console.log('Email is valid');
}, (error) => {
console.error('Something went wrong', error);
});

Related

post request on form with validation

i built a registration form and validated it using javaScript. but i want after a user filled the form, it should post to the server. i am confused on where to place my httpRequest function. i don't know if its after validation or inside the validation function
This is my validation function
function formregister(e){
if (first_name.value=== "" || last_name.value=== "" || user_id.value==="" || id_type.value=== ""
|| id_no.value=== "" || address.value==="" || !terms.checked) {
var fPassResult = '1';
} else{
var fPassResult = '0';
}
if(fPassResult === "1") {
window.location = "register.html";
}else{
Swal.fire({
type: 'success',
title: 'Your Registration has been Submitted Successfully',
text: 'Click Ok to Login',
timer: 10000
}
).then(function(){
window.location="Login.html";
})
}
e.preventDefault();
};
**And this is my post request function**
function registerationApiCall(e){
var data = {
"user_id":"user_id.value",
"user_pin": "user_pin.value",
"first_name":"first_name.value",
"last_name":"last_name.value",
"address":"address.value",
};
fetch("jehvah/api",{
type : 'POST',
data : data,
dataType : 'JSON',
encode : true,
success: function (response, status, xhr) {
if (result==="OK") {
console.log("success");
}else{
console.log("bad");
}
},
error: function (xhr, status, error) {
console.log("something went wrong");
}
});
}
Please kindly check my post request function, i dont know if i am doing it the right way
Hi ✌ when fPassResult === "0" in this case inside else{} call registerationApiCall()
you tell the user it's a success after you get OK from the server which is Asynchronous call
& inside fetch response you call swal.fire
for this code to work your server when checks the database & every thing is ok returns a msg like this {"msg":"OK"}
CODE:
else{
registerationApiCall()
}
function registerationApiCall becomes
fetch('jehvah/api',
{ method: 'POST',headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
if (result.msg="OK") {
console.log("success");
Swal.fire({
type: 'success',
title: 'Your Registration has been Submitted Successfully',
text: 'Click Ok to Login',
timer: 10000
}).then(function(){window.location="Login.html";})
}else{ console.log("usres exsists / etc");}
})
.catch((error) => {
console.log("something went wrong");
});
}
Also in the request payload you sent a group of strings not the variables containing the form values
Here
var data = {
"user_id":"user_id.value",
"user_pin": "user_pin.value",
"first_name":"first_name.value",
"last_name":"last_name.value",
"address":"address.value",
};
Change that to
var data = {
"user_id":user_id.value,
"user_pin": user_pin.value,
"first_name":first_name.value,
"last_name":last_name.value,
"address":address.value
};
Looking at the fetch documentation (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch), success and error does not exists.
The fetch function returns a Promise, so you can handle results as any Promise should do:
fetch("jehvah/api", {
method: 'POST',
body : JSON.stringify(myDataObject)
})
.then(blob => blob .json())
.then(result => console.log('Success!!))
.catch(e => console.log('Failure :('))

I need to send an alert back to the user when there is no records found

This is my post request from nodejs server
app.post('/api/users', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
console.log(req.body);
var data = req.body;
db.collection('users').findOne({
username: data.username
}, (err, result) => {
if (result === null) {
db.collection('users').insertOne(data, function (err) {
if (err) throw err;
console.log("Record inserted!");
res.status(200).send("recordInserted");
})
} else {
console.log("Already exists");
res.status(500).send("userExists");
}
})
})
This is my ajax request
$('#signupForm').on('submit', function () {
var userData = {
fullName: $("#fullName").val(),
username: $("#username").val(),
password: $("#password").val(),
email: $("#email").val()
};
$.ajax({
type: "post",
data: userData,
dataType: "text",
url: "/api/users",
function (data, status) {
if(data== 'recordInserted'){
alert("Recors inserted");
console.log("Inserted \n" + data +"\n" + status);
}
else if(data == 'userExists') {
alert("User exists");
console.log(data + "\n " + status);
}
}
});
});
I cant send back the response to the ajax request and because of that the page doesn't reload or show an error if the user already exists
As a first order of business, the preferred way for awhile now to handle responses in AJAX has been to utilize deferred objects.
let request = $.ajax({url: 'google.com', type:'get'});
request.done(function(response){
// handle response
});
Beyond that, your back-end looks to be fine.
Although!
I would highly recommend changing how you go about error handling on the server-side. If the server throws an error, the client will be left hanging until they timeout. Its best to alert the client that an error has occurred, as well.
use of e.preventDefault(); method will stop the page from being reload. you can copy paste the code
$('#signupForm').on('submit', funfunction(e) {
e.preventDefault();
let userData = {
fullName: $("#fullName").val(),
username: $("#username").val(),
password: $("#password").val(),
email: $("#email").val()
};
$.ajax({
type: "post",
data: userData,
dataType: "text",
url: "/api/users",
function (data, status) {
if(data== 'recordInserted'){
alert("Recors inserted");
console.log("Inserted \n" + data +"\n" + status);
}
else if(data == 'userExists') {
alert("User exists");
console.log(data + "\n " + status);
}
}
});
});

How to implement this in node.js?

I have the following request handler that would sign in a user with Firebase. Upon successful login, I'd like to redirect the user to another page.
Would I change window.location to another page within the (document).ready() javascript function? Or would I implement the change here, with a res.redirect (that I did try) but nothing happened, I just got back a status code within the console.
app.post('/api/sign-in', function (req, res, next) {
firebase.auth().signInWithEmailAndPassword(req.body.email, req.body.password).then(function (user) {
console.log('a new user has signed in! their e-mail address: ' + user.email + ' | User ID: ' + user.uid)
}).catch(function (error) {
console.log(error)
})
})
Call:
$("#sign-in").on('click', function (event) {
event.preventDefault()
$.ajax({
url: '/api/sign-in',
method: 'POST',
data: {
email: $('#email').val(),
password: $('#password').val()
}
});
});
Like George said, if you are doing a ajax post it won't redirect.
Maybe something like this could help you:
app.post('/api/sign-in', function (req, res, next) {
firebase.auth().signInWithEmailAndPassword(req.body.email, req.body.password).then(function (user) {
res.send({ redirect: '/profile' })
}).catch(function (error) {
console.log(error)
})})
Javascript:
$(document).ready(function () {
$('#sign-in').click(function () {
event.preventDefault()
$.ajax({
url: '/api/sign-in',
method: 'POST',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
if (typeof data.redirect === 'string') {
window.location = data.redirect;
}
}
});
});
});
Hope it can be useful.

Submitting a From to a REST API using JQuery does not work

I have a REST API running and I am posting some data to it using JQuery.
This is how my JQuery code looks:
$(document).ready(function () {
$('#login-form').submit(function () {
var user = $('#uname').val();
var pass = $('#pwd').val();
alert('username = ' + user);
alert('password = ' + pass);
var JSONObject = { 'userName': user, 'password': pass };
var jsonData = JSON.parse(JSONObject);
$.ajax({
url: 'http://127.0.0.1:8080/user/login',
method: 'POST',
data: { userName: user, password: pass },
dataType: 'JSON',
contentType: 'application/json',
success: function (data, status, jqXHR) {
//Do something
console.log('data = ' + data);
},
error: function (jqXHR, status, errorThrown) {
alert('error ' + errorThrown);
}
});
});
});
However, this code is unable to access the API. I do not get the expected message in the server log.
When the Submit button of the form is clicked, the browser gets reloaded and it shows the form inputs in the url. That is all.
My API is written using Java and this is the relevant method.
#RequestMapping(value = "/user/login", method = RequestMethod.POST)
public ResponseEntity<User> logUser(#RequestBody User user){
User loggedUser = loginService.authenticateUser(user);
if(loggedUser != null){
System.out.println("User found");
return new ResponseEntity<User>(loggedUser, HttpStatus.ACCEPTED);
}else{
//user does not exsits
System.out.println("User not found");
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
I really can't understand what is wrong. No any error is shown. Can somebody point me out why this happens and how to fix this issue.
The issue is that the browser is reloading on submit event.
You need to add preventDefault() method like this
$("#login-form").submit(function (event) {
event.preventDefault()
//further code here
This will prevent the browser from reloading

Can't update name in mongo using PUT in node express

I am having trouble updating a name in mongodb. The name is first saved by the user in a variable and passed into a function like this: putAjax(editName) Then it goes to the function here:
function putAjax(editName) {
$.ajax({
type: "PUT",
url: "/items/"+ editName,
data: editName,
dataType: 'json',
})
.done(function(result) {
console.log("result:", result);
console.log("data successfully saved:");
})
.fail(function(jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
};
I can console.log(result) and I can see the edited name so I assumed that the edit took place. Finally it makes the call to app.put on the server:
app.put('/items/:name', function(req, res) {
Item.find(req.params.name, function(err, items) {
if (err) {
return res.status(404).json({
message: 'Internal Server Error'
});
}
Item.findOneAndUpdate({
name: req.params.name
}, {
$set: {
name: req.params.name
}
}, { new: true },
function () {
res.json(items);
});
});
});
This is where the update doesn't seem to happen. When I use mongo shell, the one document I have still continues to have the same name and not the edited name. The confusing part is, why does console.log(result) show me the edited name then. I would really appreciate any help on this. Thanks.
You aren't passing a unique key to the database query. You're intention is to change the name stored in the database for an existing record but you're not doing this. Instead you are attempting to find a record that matches the new name value and you always return the value you have sent to the server.
Instead you need to pass a unique identifier with the AJAX request, using the URL makes the most sense.
function putAjax(id, editName) {
var payLoad = { name: editName };
$.ajax({
type: "PUT",
url: "/items/"+ id,
data: payLoad,
dataType: 'json',
})
.done(function(result) {
console.log("result:", result);
console.log("data successfully saved:");
})
.fail(function(jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
};
Server side code:
app.put('/items/:id', function(req, res) {
var data = req.body; // data should be validated
Item.findOneAndUpdate({ _id: req.params.id }
, { $set: data }
, { returnOriginal: false }
, function (err, result) {
if (err) {
return res.status(500).json({
message: 'Internal Server Error.'
});
}
return res.json(result);
}
);
});

Categories