Send contact details to database using ajax - javascript

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.

Related

Paypal Smart buttons with Javascript and fetch to a PHP page

I am having an intermittent problem with some Javascript code whch I cannot seem to solve and would appreciate any help with.
I have a campsite booking page which utilizes Paypal smart buttons to effect payment. In part of the Paypal Javascript 'create order' code I extract the entered customer details, populate a form using Javascript and then use fetch to post the info to a server side PHP page which inserts the info into a database.
The problem is this seems to fail 40-50% of the time ie Paypal payment is made sucessfully but the database insert appears to not be triggered.
The Javascript code is below. Any help is appreciated.
Thanks
Neville
<script>
var fname="";
var sname="";
var email="";
var mobile="";
var invoice_id="";
paypal.Buttons({
createOrder: function(data, actions) {
// This function sets up the details of the transaction, including the amount and line item details.
//1. validate form details, abort if incorrrect
if (validateForm()==false) {
alert("Incorrect Booking form data provided, aborting payment function.\r\n\r\nPlease recheck Booking form data and resubmit.");
//actions.disable();
return false;
}
//2. extract customer info from webpage
try {
email = document.forms["bookingform"]["email"].value;
invoice_id=document.forms["bookingform"]["invoice_id"].value;
fname= document.forms["bookingform"]["fname"].value;
sname = document.forms["bookingform"]["sname"].value;
mobile = document.forms["bookingform"]["mobile"].value;
if (invoice_id=="") {
invoice_id= sname.toUpperCase();
invoice_id=invoice_id+" ";
invoice_id=invoice_id.substring(0,3)+"-";
invoice_id=invoice_id+(100000 + Math.floor(Math.random() * 900000));
invoice_id=invoice_id.substring(0,10);
document.forms["bookingform"]["invoice_id"].value=invoice_id;
}
var tot_night = document.getElementById('tot_nights').innerHTML;
var tot_amt=document.getElementById("tot_amt").innerHTML;
tot_amt = tot_amt.replace("$", "");
var date_from = document.forms["bookingform"]["date_from"].value;
var date_to = document.forms["bookingform"]["date_to"].value;
var vehicle_rego = document.forms["bookingform"]["vehicle_rego"].value;
var no_adults = document.forms["bookingform"]["no_adults"].value;
var no_children = document.forms["bookingform"]["no_children"].value;
var power = document.forms["bookingform"]["power"].checked;
var tent_hire = document.forms["bookingform"]["tent_hire"].checked;
if (power=='true' || power==true) {
power ="Yes";
} else {
power="No";
}
if (tent_hire=='true' || tent_hire==true) {
tent_hire ="Yes";
} else {
tent_hire="No";
}
var street_address = document.forms["bookingform"]["street_address"].value;
var locality = document.forms["bookingform"]["locality"].value;
var package_type = document.forms["bookingform"]["package_type"].value
var voucher = document.forms["bookingform"]["voucher"].value
var notes = document.forms["bookingform"]["notes"].value
//$('#ref_fld').val(details.id);
$('#ref_fld').val('0');
} catch(err) {}
//3. create form, insert data
var formdata = new FormData();
if (formdata) {
try {
formdata.append("post_function","make_booking");
formdata.append("notes", notes);
formdata.append("invoice_id", invoice_id);
formdata.append("voucher", voucher);
formdata.append("package_type", package_type);
street_address=street_address.replace('"', '');
street_address=street_address.replace("'", "");
notes=notes.replace('"', '');
notes=notes.replace("'", "");
formdata.append("locality", locality);
formdata.append("street_address", street_address);
formdata.append("vehicle_rego",vehicle_rego);
formdata.append("trans_id",'0');
formdata.append("tot_amt",tot_amt);
formdata.append("tot_night",tot_night);
formdata.append("tent_hire",tent_hire);
formdata.append("power",power);
formdata.append("no_children",no_children);
formdata.append("no_adults",no_adults);
formdata.append("date_to",date_to);
formdata.append("date_from",date_from);
formdata.append("mobile",mobile);
formdata.append("email",email);
formdata.append("sname",sname);
formdata.append("fname",fname);
} catch(err) {}
//4. post form
const url = '/includes_macas/mysql_functions.php';
fetch(url, {
method: 'POST',
body: formdata
}).catch(function(error) {
console.log(error); // Display error if there is one.
})
}
return actions.order.create({
payer: {
name: {
given_name: fname,
surname: sname
},
email_address: email,
phone: {
phone_type: "MOBILE",
phone_number: {
national_number: mobile
}
}
},
purchase_units: [{
invoice_id: invoice_id,
amount: {
value: tot_amt
}
}],
application_context: {
shipping_preference: "NO_SHIPPING"
}
});
},
onClick: function() {
//$('#wait').show();
},
onApprove: function(data, actions) {
.......
Do not use actions.order.create() / .capture() on the client side and then record to a database, since there is no guarantee of being able to record a successful capture on your server if you do that.
Instead, for a proper server integration, create two routes -- one for 'Create Order' and one for 'Capture Order', as documented here. Your routes should return/output JSON (and only JSON). The capture route should check for success after calling PayPal and do any database writing before returning JSON to the client.
Pair your two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server

How to POST data from client to node server

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?

Console says onsubmit function doesn't exist for register form, even though it clearly does

So I have a register form, as thus:
<form name="register" action="" method="POST" onsubmit="register()" autocomplete="off">
...
</form>
And I know that every child of this form is functioning.
Then, below in a <script> tag I have my main function which is called when the above form is submitted. And I know that everything outside of the register function is running. However, when I input random values into each field of my form, and press submit, the console shows that the register() function called in the onsubmit attribute of my form does not exist. I can't seem to find the problem here:
//Global Vars
var firebaseConfig = { ...
};
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
var registerButton = document.querySelector("#registerButton");
//Main Register Function
function register() {
event.preventDefault();
//Locally Global Variables
var fullName = document.forms["register"]["fullName"].value;
var username = document.forms["register"]["username"].value.toLowerCase();
//The MD5 is a way to hash the password, that way the real password is safe and only the hash is used
var password = md5(document.forms["register"]["password"].value);
var serviceProvider = document.forms["register"]["serviceProvider"].value;
//Simple If Statement that adds appropriate email suffix based on Service Provider
if (serviceProvider === "Verizon") {
serviceProvider = "#vtext.com";
} else if (serviceProvider === "ATT") {
serviceProvider = "#txt.att.net";
} else if (serviceProvider === "TMobile") {
serviceProvider = "#tmomail.net";
} else if (serviceProvider === "Sprint") {
serviceProvider = "#messaging.sprintpcs.com";
}
var phoneNumber = document.forms["register"]["phoneNumber"].value + serviceProvider;
var emailAddress = document.forms["register"]["emailAddress"].value;
//Checks The Database If The Username Is Already Taken Or Not
db.collection("Users").where("username", "==", username).get()
.then(function(querySnapshot) {
//Checks Each Individual Result -- If there are no results, than this code will not run
try {
querySnapshot.forEach(function(doc) {
//If any result exists, stop here
if (doc.data()) {
alert("I'm sorry but this username is already taken!! Please Try Another One");
throw "Error";
}
});
} catch (error) {
if (error === "Error") {
return;
}
}
//If not
//Add All Of The User Info To The Database
db.collection("Users").doc(username).set({
fullName: fullName,
username: username,
password: password,
phoneNumber: phoneNumber,
emailAddress: emailAddress,
chatsInvolvedIn: []
})
.then(function() {
//If it succeeds, give user the heads up and then take them to their new homepage
alert("Your account under the username " + username + " has been sucessfully created. You will now be redirected to your homepage.");
//Place Code Underneath to Handle Keeping user Logged In For Present and Future Visits, along with redirecting to a homepage
//Code Goes Here
db.collection("Users").doc(username).get().then(function(doc) {
if (doc.exists) {
localStorage.setItem("loggedIn", JSON.stringify(doc.data()));
}
alert(localStorage.getItem("loggedIn"));
//window.location.replace("index.html");
});
})
.catch(function(error) {
//If it fails, tell user to try again later (we don't care about the error message during production, because it is unlikely after our many tests)
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
})
.catch(function(error) {
//If checking the database originally for duplicate usernames fails, then give the user the same warning as above
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
}
I know that my programming practices above aren't the best. if you could help me out, that would be great, thank you!

Can't pull up user info right after entered in indexedDB

I have a register form with an indexedDB. I have resgister/log in working. I've been trying different things to get a new register to login as soon as they register but im not sure what's going. It won't work. The localStorage sets like it should but it won't bring up the user's data.
JS:
function addObject(){
if(confirm('Are you sure you want to resgister?')){
fName = document.getElementById('fName').value;
lName = document.getElementById('lName').value;
userName = document.getElementById('uName').value;
pass = document.getElementById('password').value;
email = document.getElementById('email').value;
dob = document.getElementById('dob').value;
tel = document.getElementById('tel').value;
bio = document.getElementById('bio').value;
terms = document.getElementById('terms').value;
school = document.getElementById('school').value;
//Need loop to find radio button values
radios = document.getElementsByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
gender=radios[i].value;
}
}
//set up transaction
var mytransaction = db.transaction(['users'], "readwrite");
//get object store
var myusers = mytransaction.objectStore('users');
//Add item
var request = myusers.put(new getUser(userName,fName,lName,pass,email,dob,tel,bio,terms,school,gender));
}
// Show all results.
if(document.URL.indexOf('admin.html') > -1){
mytransaction.addEventListener('complete', showUsers);
}
//Log in new users
loginCheck(userName,pass);
/*newLocal('user',user); */
//Reset Form Fields
resetForm();
}
This is the functions I use when someone logs in.
function loginCheck(user,pass){
db.transaction("users").objectStore("users").get(user).onsuccess = function(e) {
var loggedUser = e.target.result;
if(!loggedUser){
alert('Sorry, Username does not exist. Please try again.');
}else if(pass !== loggedUser.pw ){
alert('Incorrect log in combination. Please try again.');
}else{
loggedIn(loggedUser);
populateFields(loggedUser);
loginStyle(loggedUser)
}
}
}
function loggedIn(loggedUser){
var u=loggedUser;
alert('Welcome '+u.fn+' '+u.ln+' to Macroplay');
//Set localStorage
var signedin = 'user';
var username = u.userName;
newLocal(signedin,username);
}
function getValues(){
db.transaction("users").objectStore("users").get(localStorage.user).onsuccess = function(e) {
populateFields(e.target.result);
loginStyle(e.target.result)
};
;
}
From what I can see the first part adds the user to the DB and the second portion should behave as is I was just logging normally. But it won't pull up the info from the DB.
I've tried setting the new user to localStorage which is how I recognize a user currently loggedin but that also had no effect.
This is my site: http://www3.carleton.ca/clubs/sissa/html5
It looks like you're using the onsuccess handler in the loginCheck method, but you're not when calling put on the db. My guess would be that you're checking to see if the user exists before it's actually had a chance to be added. Try this:
//Add item
var request = myusers.put(new getUser(userName,fName,lName,pass,email,dob,tel,bio,terms,school,gender));
request.onsuccess = function () {
// Show all results.
if(document.URL.indexOf('admin.html') > -1){
mytransaction.addEventListener('complete', showUsers);
}
//Log in new users
loginCheck(userName,pass);
/*newLocal('user',user); */
//Reset Form Fields
resetForm();
}

Django: Password check returning false in view when it should return true

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.

Categories