I am trying to POST the data from a form using a function to node.js server to be inserted into SQLITE. But somehow the data is not posted to the node.js server at all. These are what I have done:
client.js
//function triggered when submit button is clicked
function createInvitation() {
var id = localStorage.getItem('id');
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var email = document.getElementById("email").value;
var refno = Math.floor(Math.random()*89999999+10000000);
//i got all the data here
alert(id + name + phone + email + refno)
if (name == "" || phone == "" || email == "")
{
alert("Please fill in all details!");
}
else {
$.post('/visitors',
{
host_id: id,
visitor_name: name,
visitor_phone: phone,
visitor_email: email,
reference_no: refno
},
function(data) {
alert(data);
window.location.reload();
});
}
}
server.js
app.post('/visitors', function(request,response){
console.log('POST request received at /visitors');
var sql = 'INSERT INTO visitors(host_id, visitor_name, visitor_phone, visitor_email, reference_no) VALUES (?,?,?,?,?)';
var visitors = [request.body.host_id, request.body.visitor_name, request.body.visitor_phone, request.body.visitor_email, request.body.reference_no];
console.log(visitors);
db.run(sql, visitors, function(err) {
if (err) {
console.log("Error: "+err);
}
else {
response.status(200).redirect('generate.html');
}
});
});
Any advises will be greatly appreciated. Thanks in advance
UPDATE:
Is this correct?
Related
This is supposed to handle the form validation for a simple contact form with name, email address, website url, and 10 line comment section for project description, then hand the information as a JSON object to a php file to send to a designated email address.
When I had action="emailprocessor.php in the HTML code, the form validation went through the PHP file and not JS, and it sent properly to the designated email address.
Without the action in the html, it's supposed to flow through the JS and then to the PHP. It's not doing that.
Here is my code:
(function () {
"use strict";
const contactForm = document.getElementById('contactform');
contactForm.addEventListener('submit', validateForm);
//Messages to be put in the message element when there is an error or success...
// The last element in this array loads the preloader css.
const feedBackMessage = [
'<div class="error"><h3>Ooops!</h3><p>The name field is reqired, that\'s how I know who you are. Please fix that and try again!</p></div>',
'<div class="error"><h3>Ooops!</h3><p>You forgot to give me a valid email address. Please fix that and try again!</p></div>',
'<div class="error"><h3>Ooops!</h3><p>You forgot to enter your website. Please fix that and try again!</p></div>',
'<div class="error"><h3>Ooops!</h3><p>Please enter your project description or comment.</p></div>',
'<div class="success"><h3>Thank you!</h3><p>Your information has been sent, and we will be in touch.</p></div>',
'<div class="preloader"><div class="loading-dot"></div></div>'
];
// The actual form validation function. Added url regex.
function validateForm(event) {
event.preventDefault();
const nameField = document.getElementById('name');
const emailField = document.getElementById('email');
const siteField = document.getElementById('website');
const commentField = document.getElementById('comment');
const reName = /^[a-zA-Z]+(([\'\- ][a-zA-Z])?[a-zA-Z]*)*$/;
const reEmail = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;
const reUrl = /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/;
let errors = 0;
if (!reName.test(nameField.value)) {
displayMessage(nameField, feedBackMessage[0]);
errors++;
}
else if (!reEmail.test(emailField.value)) {
displayMessage(emailField, feedBackMessage[1]);
errors++;
}
else if (!reUrl.test(siteField.value)) {
displayMessage(siteField, feedBackMessage[2]);
errors++;
}
else if (commentField.value == "") {
displayMessage(commentField, feedBackMessage[3]);
errors++;
}
else if (errors === 0) {
sendData();
}
}
// This displays error / success messages
function displayMessage(field, message) {
document.getElementById('message').className = "show-message";
document.getElementById('message').innerHTML = message;
setTimeout(function () {
document.getElementById('message').classList.add("fadeOutElement");
setTimeout(function () {
if (field != 'success') {
document.getElementById('message').className = "hide-message";
document.getElementById(field.id).focus();
}
else {
document.getElementById('message').setAttribute("class", "hide-message");
document.getElementById('name').value = '';
document.getElementById('email').value = '';
document.getElementById('website').value = '';
document.getElementById('comment').value = '';
}
}, 2000);
}, 2000);
//puts messages in the DOM??
}
function sendData() {
document.getElementById('message').className = "show-message";
document.getElementById('message').innerHTML = feedBackMessage[5];
setTimeout(async () => {
const formdata = new FormData(contactForm);
const fetchPromise = await fetch('emailprocessor.php', { method: 'POST', body: formdata });
const data = await fetchPromise.json();
console.log(data.result);
if (data.result == "success") {
displayMessage('success', feedBackMessage[4]);
}
}, 2000);
}
//actually sends the data asynchronously or so it claims
});
So basically i store the details entered by the user in the register form into local HTML storage... And i have checked that the details ARE stored in local storage, however, when i try to log in with such information (username and password) in the login form.... it doesn't work. So how would i be able to log in the login form successfully?? In other words, how would i be able to get the data for username and password entered in the register form (which is stored in local storage) and use that to compare with user's input in login form to validate the login process?? Here are files:
You have to compare them to user and pass, not username and password:
var entry = localStorage.getItem("entry");
console.log("username: " + entry.user + "password: " + entry.pas);
if(username.value == entry.user && password.value == entry.pass) {
alert('You have successfully logged in.');
}
In the browser pres CTRL + SHIFT + I, and if it's not open select "Console"
These lines won't work:
var storedUserName = localStorage.getItem('UserName');
var storedPassWord = localStorage.getItem('PassWord');
var storedEmailAddress = localStorage.getItem('EmailAddress');
savedata() doesn't save each field to its own item, it just saves the entry object as a whole. So you need to retrieve that and parse it.
var entryJSON = localStorage.getItem('entry');
if (!entryJSON) {
alert("Nothing stored!");
return;
}
var entry = JSON.parse(entryJSON);
var storedUserName = entry.user;
var storedPassWord = entry.pass;
var storedEmailAddress = entry.email;
To search allEntries, you need to use a loop:
function validlogin(event) {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var entriesJSON = localStorage.getItem('allEntries');
if (!entriesJSON) {
alert("Nothing stored!");
event.preventDefault();
return;
}
var allEntries = JSON.parse(entriesJSON);
for (var i = 0; i < allEntries.length; i++) {
var entry = allEntries[i];
var storedUserName = entry.user;
var storedPassWord = entry.pass;
var storedEmailAddress = entry.email;
if (username == storedUserName && password == storedPassWord) {
alert("Successfully logged in!");
return;
}
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location="Login.html";
}
I have a page that allows users to select contact names and details from their mobile device, what I am trying to do is then add those details to a mysql database using ajax.
Original code to get contact details from device.
function select_a_contact()
{
intel.xdk.contacts.chooseContact();
}
document.addEventListener('intel.xdk.contacts.choose', function(evt){
if (evt.success == true)
{
var contactID = evt.contactid;
//this function retrieves information of a contact based on its id.
var contactInfo = intel.xdk.contacts.getContactData(contactID);
var firstName = contactInfo.first;
var lastName = contactInfo.last;
var phoneNumbers = contactInfo.phones;
var emails = contactInfo.emails;
var address = contactInfo.addresses;
alert(firstName + lastName);
}
else if (evt.cancelled == true)
{
alert("Choose Contact Cancelled");
}
});
Here is my modified code where I have added some code to send the contact details to a php page. when I select a contact I don't get get any errors, but the Alert doesn't trigger so i am assuming that my code isn't working. If i use the ajax code in a form environment it works perfectly, i have tried writing this several different ways but the ajax code doesn't seem to trigger.
function select_a_contact()
{
intel.xdk.contacts.chooseContact();
}
document.addEventListener('intel.xdk.contacts.choose', function(evt){
if (evt.success == true)
{
var contactID = evt.contactid;
//this function retrieves information of a contact based on its id.
var contactInfo = intel.xdk.contacts.getContactData(contactID);
var firstName = contactInfo.first;
var lastName = contactInfo.last;
var phoneNumbers = contactInfo.phones;
var emails = contactInfo.emails;
var address = contactInfo.addresses;
$.ajax({
type: "POST",
url: "http://www.domian.co.uk/app/build.php",
data: {
var firstName = contactInfo.first;
var lastName = contactInfo.last;
var phoneNumbers = contactInfo.phones;
var emails = contactInfo.emails;
var address = contactInfo.addresses;
},
success: function(){
alert(firstName);
}
});
alert(firstName + lastName);
}
else if (evt.cancelled == true)
{
alert("Choose Contact Cancelled");
}
});
Your data portion is wrong. Try this instead:
data: {
firstName: firstName,
lastName: lastName,
phoneNumbers: phoneNumbers,
emails: emails,
address: address
},
... or ...
data: {
firstName: contactInfo.first,
lastName: contactInfo.last,
phoneNumbers: contactInfo.phones,
emails: contactInfo.emails,
address: contactInfo.addresses
},
Using the second you can get rid of all the new variable declarations, clean your code up a bit. You technically don't need them.
No expert when it comes to JS/Jquery, but im trying to use this code, and once the registration sign up is done correctly, and the information is stored, instead of a alert box, i wanna have it redirect to another web page... This is what ive got so far, ive tried a few things, but none seem to be working... What am i doing wrong, and how to fix this?
$(document).ready(function () {
$("#register").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function (data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
if (data == "index.html"){
//...
}
Stripped version.
$(document).ready(function () {
$("#register").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function (data) {
// check if registration ok
location.href = 'index.html';
});
});
});
As part of form validation, the password and password2 are compared. This is part of a simplified ajax request system for an extremely small site returning small amounts of data (so i don't use JSON). The idea/objective/summery of the program is that it tries to log in the user. If the user does not exist, it asks the client side to load/reveal the form for new users (just an added password2 field and asks for a pen name). Here is the file, I've marked the sport where the program freezes with #*********
Forms.py (error is not here):
class new_user(forms.Form):
username = forms.EmailField()
password = forms.PasswordInput()
password2 = forms.PasswordInput()
pen_name = forms.CharField(max_length=30)
Views.py, where the error is:
def user_log_in(request):
#add stuff for ajax request
user_pass = log_in(request.POST)
er = []
if user_pass.is_valid():
print "valid"
cleaned_info = user_pass.cleaned_data
user_object = User.objects.filter(email = cleaned_info['username'])
if user_object.exists():
logged_in_user = auth.authenticate(username=cleaned_info['username'], auth_password=cleaned_info['password'])
#add in is_active
if logged_in_user is not None:
auth.login(request, logged_in_user)
return HttpResponseRedirect('/home')
else:
er.append("Incorrect Password")
else:
new_user_pass = new_user(request.POST)
if new_user_pass.is_valid():
cleaned_info_new = new_user_pass.cleaned_data
print "check points"
if cleaned_info_new['password'] == cleaned_info_new['password2']: #********
print "clean"
new_user_query = creat_user(
username=cleaned_info_new['username'],
password=cleaned_info_new['password'],
email=cleaned_info_new['username']
)
new_user_query.save()
msg = ""
try:
send_mail("Activate", msg, 'mrgnippy#gmail.com',
[cleaned_info['username']], fail_silently=False)
except:
er.append("Error Sending Email")
else:
er.append('Passwords are not the same')
elif "TN" in request.POST:
print "TN"
for e in new_user_pass.errors:
er.append(e)
#elif to check for is_active
else:
print "n_usr"
return HttpResponse('n_usr')
else:
for e in user_pass.errors:
er.append(e)
for e in er:
print"-"
print e
print"-"
return HttpResponse('SOS')
The django debug page says the following:
KeyError at /ajax/login 'password' Request Method: POST Request URL: http://127.0.0.1:8000/ajax/login Django Version: 1.4 Python Executable:
The post variable stuff in the error is this (I blanked out my email and):
GET: No GET data POST: username = u'********#aol.com' TN = u'TN' password2 = u'test' password = u'test' pen_name = u'testing123' FILES: No FILES data
Just in case the problem is here, I've included the javascript file.
n_usr = false;
function log_in () {
if(!$('#pass_enter').hasClass('#usr_enter')){
password = $('#pass_enter').val();
}else{
password = '';
}
if(!$('#usr_enter').hasClass('blur_field')){
username = $('#usr_enter').val();
}else{
username = '';
}
alert(username);
if(!n_usr){
$.post('/ajax/login',{password: password, username: username}, function(data) {
if(data == "n_usr"){
$('#new_user_entry').show('slow');
n_usr = true;
}
else {
}
})
}else {
if (!$('#pass_re_enter').hasClass('blur_field')){
password2 = $('#pass_re_enter').val();
}else {
password2 = '';
}
if (!$('#pass_re_enter').hasClass('blur_field')){
penname = $('#pen_enter').val();
}else {
penname = '';
}
$.post('/ajax/login', {password: password, password2: password2, username: username, pen_name: penname, TN: "TN"}, function(data) {
if(data == "e_act"){
} else {
}
});
}
}
I just noticed that I used the wrong fields in the forms.py file. Problem solved.