Jquery Notification on Ajax POST Success - forms

I have an issue with a some of the jQuery notifications I have created to trigger based on information echo'd from a PHP file after a user submits a sign up HTML form via AJAX. The notifications for errors work, but not for a successful post to the database. I know that the success notification should show because the data is validated and written to the database and AJAX post is successful. However the success notification does not want to work. What could be the reason for this technicality?
I have the following set up:
signup.html (contains the following ajax within the page*):
function registerUser(formKey) {
$.ajax({
type:"POST",
url:"engine/new_user.php",
data: $("#"+formKey).serialize(),
cache:false,
success: function(data) {
if(data == -3){
$("html, body").animate({ scrollTop: 0 }, 600);
$("#user-exists-notification").fadeIn(1000);
}
if(data == -4){
$("#account-created").fadeIn(1000);
}
if(data == -1){
$("html, body").animate({ scrollTop: 0 }, 600);
$("#fields-complete-notification").delay(1000).fadeIn(1000);
}
if(data == -2){
$("html, body").animate({ scrollTop: 0 }, 600);
$("#pw-confirm-notification").delay(1000).fadeIn(1000);
}
},
error: function(data) {
}
});
}
new_user.php
require("register-classes.php");
$register=new Register($_POST['fname'], $_POST['lname'], $_POST['email'], $_POST['sex'], $_POST['birthdate'], $_POST['phone'], $_POST['country'], $_POST['alias'], $_POST['handle'], $_POST["password"], $_POST["cpassword"], $_POST['network']);
if($register->checkFields()== false){
echo -1;
} else if($register->confirmPasswords()== false){
echo -2;
}else if($register->registerUser()!=false){
echo -4;
} else if($register->registerUser()==false){
echo -3;
}
and register-classes.php (which contains classes for processing sign up form)
class Register {
public function __construct($fname, $lname, $mail, $sex,
$birthday, $phonenumber, $regCountry, $alias, $username,
$password, $conf_password, $network_site) {
//Copy Constructor
$this->site=$network_site;
$this->firstname=$fname;
$this->lastname=$lname;
$this->email=$mail;
$this->sex=$sex;
$this->birthdate=$birthday;
$this->phone=$phonenumber;
$this->country=$regCountry;
$this->displayname=$alias;
$this->handle=$username;
$this->salt="a2cflux9e8g7ds6ggty589498j8jko007876j89j8j7";
$this->password=crypt($this->salt.$password);
$this->joindate=date("Y-m-d H:i:s");
$this->confirm_password1=$password;
$this->confirm_password2=$conf_password;
}
public function registerUser(){
$database=new Database();
$database->getConnection();
$database->startConnection();
//Check database to insure user and email address is not already in the system.
$checkUsers= mysql_query("SELECT network_users.network_id
FROM network_users, network_profile
WHERE network_users.handle = '$this->handle'
OR network_profile.email = '$this->email'");
$numRecords= mysql_num_rows($checkUsers);
if($numRecords == 0){
$addUser= mysql_query("INSERT INTO network_users(handle, password, date_created, parent_network, site_created, active, account_type, del)
values('$this->handle', '$this->password', '$this->joindate',' fenetwork', 'network', 'active', 'standard', 'F')") or die(mysql_error());
$networkId=mysql_insert_id();
$addProfile= mysql_query("INSERT INTO network_profile(network_id, first_name, last_name, email, sex, birthdate, phone, country, display_name, del)
values('$networkId', '$this->firstname', '$this->lastname', '$this->email','$this->sex', '$this->birthdate', '$this->phone', '$this->country', '$this->displayname', 'F')") or die(mysql_error());
$this->addUser;
$this->addProfile;
return true;
}
else{
return false;
}
}
public function checkFields(){
if(($this->firstname)!="" && ($this->lastname)!="" && ($this->email)!="" && ($this->sex)!="" &&
($this->birthdate)!="" &&($this->country)!="" && ($this->handle)!="" && ($this->password)!=""){
return true;
} else {
return false;
}
}
public function confirmPasswords(){
if($this->confirm_password1==$this->confirm_password2){
return true;
} else {
return false;
}
}
private $site, $firstname, $lastname, $email,
$sex, $birthdate, $phone, $country, $displayname,
$handle, $password, $salt, $joindate, $confirm_password1, $confirm_password2;
protected $addUser, $addProfile;
}

I found the issue. The issue was due to printf() functions that were apart of a few class members in the database class. They were causing an interruption with the function completing and returning the boolean value true or false in registerUser();
Thank you all for your help and assistance. I would give up a vote up, but I don't have enough reputation points. haha.

Related

Multiple save operations in async.forEachOf

I have a loop through some payments in a mongo collection. All the payments with payoutdate == today() must be exported and written to an sepa file, so we can handle the payments by bank.
The payments doesn't have an invoicenumber while they are created and we generating one when the payment is processed (exported via the above function).
The problem is, that when we run the function with multiple payments to be exported, all the payments are getting the same invoice number. So it looks like, that the last save operation is not completed before the next payment is processed.
How can I archieve that every payment is getting an increasing number?
This is the loop function:
const fs = require('fs');
const async = require('async');
const DateDiff = require('date-diff');
const SEPA = require('sepa');
const shopService = require(path.join(__dirname, '..', 'services', 'shop.service'));
async.forEachOf(payments, function(payment, key, paymentDone){
var diff = new DateDiff(new Date(payment.payoutDate), new Date());
if(payment.payoutDate && payment.amount > 0 && payment.completed == false && payment.exported == false && diff.days() <= 0){
//payment has amount, is not completed and is not exported, create an SEPA transfer, and set the payment to completed
//but first create an invoicenumber
orderService.updateOrderPayment(payment.orderId, {generateInvoiceNumber: true}, function(err, result){
if(err){
console.log("error updating payment", err);
}
//reget the payment to avoid duplicated invoice numbers
orderService.getPayment(result.orderId, function(err, payment){
if(err){
console.log("error getting payment", err);
}
Shop.findOne({_id: payment.shopId}).exec(function(err, shop){
if(shop && shop.bankAccountNumber && shop.accountHolder && shop.bicCode){
//create transaction and add this to the file
}else{
var result = {
paymentID: payment._id,
orderId: payment.orderId,
status: payment.status,
message: "shop does not have an iban, accountholder or biccode",
shop: shop.nameSlug
}
resultArray.push(result);
console.log("shop does not have an iban, accountholder or biccode", shop.nameSlug);
paymentDone();
}
orderService.updateOrderPayment(payment.orderId, {status: 'completed'}, function(err, result){
orderService.updateOrderStatusById(payment.orderId, {status: 'Granted', date: new Date(), comment: null});
var result = {
paymentID: payment._id,
orderId: payment.orderId,
status: payment.status,
message: "payment exported",
}
resultArray.push(result);
counter++;
paymentDone();
})
})
})
})
}else{
var result = {
paymentID: payment._id,
orderId: payment.orderId,
status: payment.status,
message: "order already processed"
}
resultArray.push(result);
paymentDone();
}
}, function(){
if(resultArray.length == payments.length){
//console.log("Result", resultArray);
if(counter == 0){
res.status(200).json({"message":"No orders to export", resultArray});
}else{
res.set({"Content-Disposition":"attachment; filename=\"sepa.xml\""});
res.send(doc.toString());
}
}
})
The orderService contains the following functions (relevant to this question)
function updateOrderPayment(orderId, paymentStatus, callback){
console.log("updateOrderPayment");
if(!paymentStatus){
return callback("No payment details provided");
}else{
if(!paymentStatus.comment){
paymentStatus.comment = null;
}
}
getPayment(orderId, function(err, payment){
if(err)
return callback(err);
handlePayment(payment, paymentStatus, function(result){
result.save(function(err, result){
if(err){
return callback(err);
}
console.log("payment saved");
return callback(null, result);
})
})
})
}
function handlePayment(payment, paymentStatus, callback){
if(paymentStatus.status){
var status = {
status: paymentStatus.status,
comment: paymentStatus.comment,
date: Date.now()
}
payment.status.push(status);
}
if(paymentStatus.generateInvoiceNumber){
console.log("generateInvoiceNumber");
var invoiceNumber =0;
Payment.findOne({invoiceNumber: {$exists:true}}).sort({_id: -1}).exec(function(err, latestPaymentsWithNumber){
if(latestPaymentsWithNumber && latestPaymentsWithNumber.invoiceNumber){
invoiceNumber = latestPaymentsWithNumber.invoiceNumber.split("-")[1];
}
var date = new Date();
payment.invoiceNumber = date.getFullYear().toString() + date.getMonth().toString() + "-" + (parseInt(invoiceNumber)+1);
console.log("number", payment.invoiceNumber);
return callback(payment);
})
}
if(paymentStatus.status == 'returned' || paymentStatus.status == 'cancelled'){
payment.cancelled = true;
payment.amount = 0;
payment.payoutDate = null;
return callback(payment);
}
if(paymentStatus.status == 'completed'){
payment.completed = true;
payment.exported = true;
payment.payoutDate = null;
return callback(payment);
}
}
function getPayment(orderId, callback){
Payment.findOne({orderId: orderId}).exec(function(err, payment){
if(err){
return callback(err);
}
return callback(null, payment);
})
}
you have 2 choices:
1) implement callbacks to your save operation within scope
x.forEach(function(_x) {
_x.save(function(err) { });
});
2) break out your functions to async units or use an async library
function async(x, cb) {
x.operations(cb)
}
function series(x) {
if (x) {
async(x, function() { series(xs.pop()); });
} else // finished
}
series(xs.pop()); // xs is the array you're iterating
Thanks to both of the reply's! A combination was the solution.
I have changed the query to find the last invoiceNumber to
Payment.find({invoiceNumber: {$ne:null}}).sort({date: -1}).limit(1).exec(function(err, latestPaymentsWithNumber){
I use now async.eachSeries to iterate over payments:
async.eachSeries(payments, function(payment, paymentDone){
And I do a result.save in the first callback to asume I have the right data
result.save(function(err, payment){

Ionic2 - http get is not working

I have written a authentication service to authenticate user name and password in a Login Page. The code below is the service.
public login(credentials) {
if (credentials.username === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
let apiURL = 'http://localhost/timeclock/api/login?usercode=' + credentials.username +
'&password=' + credentials.password ;
return Observable.create(observer => {
this.http.get(apiURL).map(res => res.json()).subscribe(data => {
if (data.success === 'true')
{
this.currentUser.name = data.data.user_name;
this.currentUser.email = data.data.user_email;
observer.next(true);
observer.complete();
} else {
observer.next(false);
observer.complete();
}
});
});
}
}
When the user name and password is submitted, the URL is correctly called with the right parameters.
The http call takes very long time to complete. Also, no response is returned.
It takes only two or three seconds to get the response when I call the URL with the same parameters in the browser.
Any idea on how to fix this?
You don't need to create a new Observable you can refactor like this.
public login(credentials) : Observable<boolean> {
if (credentials.username === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
let apiURL = 'http://localhost/timeclock/api/login?usercode=' + credentials.username +
'&password=' + credentials.password ;
return this.http.get(apiURL).map(res => res.json())
.map(data =>
{
if(data.success){
this.currentUser.name = data.data.user_name;
this.currentUser.email = data.data.user_email;
return true;
}else{
return false;
}
});
}
}

How to set up profiles and sessions in Firebase and Ionic using Facebook Auth

I am very new to Firebase and struggling to set up a system where a user logs in via Facebook, and his/her profile picture is saved in a database.
I have a users and also a uids array in Firebase. What I want the flow to be is:
Login via Facebook
Store some memory of the user so they don't have to login again on the app, or perhaps store into the uids and users array
Get the existing name, location to fill into a profile section of the app
Update any of these to then fill into the Firebase users database, as well as add new fields e.g. location
Here is my current setup:
Login Controller:
.controller('LoginCtrl', ['Auth', '$state', '$location', '$scope', '$rootScope', '$firebaseAuth', '$window',
function (Auth, $state, $location, $scope, $rootScope, $firebaseAuth, $window) {
// check session
//$rootScope.checkSession;
// Create a callback to handle the result of the authentication
$scope.user = {
email: this.email,
password: this.password
};
$scope.validateUser = function (user) {
$rootScope.show('Please wait.. Authenticating');
console.log('Please wait.. Authenticating');
var email = this.user.email;
var password = this.user.password;
/* Check user fields*/
if (!email || !password) {
$rootScope.hide();
$rootScope.notify('Error', 'Email or Password is incorrect!');
return;
}
/* All good, let's authentify */
Auth.$authWithPassword({
email: email,
password: password
}).then(function (authData) {
console.log(authData);
//$rootScope.userEmail = user.email;
$window.location.href = ('#/app/meals');
$rootScope.hide();
}).catch(function (error) {
console.log("Login Failed!", error);
if (error.code == 'INVALID_EMAIL') {
$rootScope.notify('Invalid Email Address');
}
else if (error.code == 'INVALID_PASSWORD') {
$rootScope.notify('Invalid Password');
}
else if (error.code == 'INVALID_USER') {
$rootScope.notify('Invalid User');
}
else {
$rootScope.notify('Oops something went wrong. Please try again later');
}
$rootScope.hide();
//$rootScope.notify('Error', 'Email or Password is incorrect!');
});
};
$scope.loginWithGoogle = function () {
Auth.$authWithOAuthPopup('google')
.then(function (authData) {
$state.go($location.path('app/meals'));
});
};
$scope.loginWithFacebook = function () {
Auth.$authWithOAuthPopup('facebook')
.then(function (authData) {
console.log(authData);
$state.go($location.path('app/meals'));
})
.catch(function(error){
if (error.code === "TRANSPORT_UNAVAILABLE") {
Auth.$authWithOAuthRedirect("facebook").then(function (authData) {
// User successfully logged in. We can log to the console
// since we’re using a popup here
console.log(authData);
$state.go($location.path('app/meals'));
});
} else {
// Another error occurred
console.log(error);
}
});
};
}
])
Key functions like get session I want in $rootScope:
.run(function ($ionicPlatform, $rootScope, $firebaseAuth, $firebase, $window, $ionicLoading) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
$rootScope.userEmail = null;
$rootScope.baseUrl = 'https://[myappurl.firebaseio.com/';
var authRef = new Firebase($rootScope.baseUrl);
$rootScope.auth = $firebaseAuth(authRef);
$rootScope.authData = authRef.getAuth();
$rootScope.show = function(text) {
$rootScope.loading = $ionicLoading.show({
content: text ? text : 'Loading..',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
};
$rootScope.hide = function() {
$ionicLoading.hide();
};
$rootScope.notify = function(text) {
$rootScope.show(text);
$window.setTimeout(function() {
$rootScope.hide();
}, 1999);
};
$rootScope.logout = function() {
authRef.unauth();
$rootScope.authDataCallBack;
};
$rootScope.checkSession = function() {
if ($rootScope.authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
$rootScope.userEmail = user.email;
$window.location.href = ('#/app/meals');
} else {
console.log("No session so logout");
$rootScope.userEmail = null;
$window.location.href = '#/auth/signin';
}
}
$rootScope.authDataCallBack = function(authData) {
if ($rootScope.authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
} else {
console.log("User is logged out");
$window.location.href = '#/auth/signin';
}
};
});
})
The profile page:
<ion-view view-title="Profile">
<ion-content class="has-header">
<div class="list card">
<div class="item">
<h2>{{user.name}}</h2>
<p>{{user.city}}</p>
</div>
<!--https://github.com/israelidanny/ion-profile-picture-->
<!--<div class="item item-body">-->
<!--<img src="http://graph.facebook.com/{{user.id}}/picture?width=270&height=270"/>-->
<!--</div>-->
</div>
</ion-content>
</ion-view>
Auth factory:
app.factory('Auth', ['rootRef', '$firebaseAuth', function (rootRef, $firebaseAuth) {
return $firebaseAuth(rootRef);
}]);
If it helps, here is my SignUpCtrl which pushes items into the users array and also stores an array of uids of users already set up in the app.
.controller('SignUpCtrl', [
'$scope', '$rootScope', '$firebaseAuth', '$window', 'Auth',
function ($scope, $rootScope, $firebaseAuth, $window, Auth) {
$scope.user = {
firstname: this.firstname,
lastname: this.lastname,
email: "",
password: ""
};
$scope.createUser = function () {
var firstname = this.user.firstname;
var lastname = this.user.lastname;
var email = this.user.email;
var password = this.user.password;
if (!email || !password) {
$rootScope.notify("Please enter valid credentials");
return false;
}
$rootScope.show('Please wait.. Registering');
$rootScope.auth.$createUser(
{email: email, password: password})
.then(function (user) {
console.log('user is created');
$rootScope.hide();
$rootScope.userEmail = user.email;
var usersRef = new Firebase('https://foodsharingapp.firebaseio.com/users');
var keyRef = usersRef.push({
'uid': user.uid,
'email': email,
'firstname': firstname,
'lastname': lastname
});
var uidRef = new Firebase('https://[myapp].firebaseio.com/uids/' + user.uid + '/' + keyRef.key());
uidRef.set({'registered': true});
$window.location.href = ('#/app/meals');
}, function (error) {
console.log('error unfortunately');
$rootScope.hide();
if (error.code == 'INVALID_EMAIL') {
console.log('invalid email');
$rootScope.notify('Invalid Email Address');
}
else if (error.code == 'EMAIL_TAKEN') {
console.log('email taken');
$rootScope.notify('Email Address already taken');
}
else {
console.log('not sure what happened');
$rootScope.notify('Oops something went wrong. Please try again later');
}
});
}
Questions:
I want to call $rootScope.authDataCallBack(authData) on any controller to get the name and any details of the user_id logged in, however this is not working. Am I thinking about this right? How can I use my $rootScope functions as ways to obtain global information?
When I log in I see the Facebook object appearing fine, should I use the Facebook ID as a uid to store in my array?
On any view, how can I use the session uid or authData to then match against my list of users in the user array and pull out more detailed user info? Is there some pseudocode I can use and would this be in every function in my controller, or would it be split between factory and controller?

SIPml5 one sided voice

Below is the code of my dialer. I can register and connect calls successfully with the below code. But, after call is connected only the other end (non sipml5) can hear voice. But, the sipml5 side can not hear anything.However, I could connect and pass voice using the sipml5 client from sipml5 website(sipml5.org/call.htm). I must be doing something wrong, but cant figure out what.
<script src="api/SIPml-api.js" type="text/javascript"> </script>
<script type="text/javascript">
var readyCallback = function(e){
createSipStack(); // see next section
};
var errorCallback = function(e){
onsole.error('Failed to initialize the engine: ' + e.message);
}
SIPml.init(readyCallback, errorCallback);
var sipStack;
var callSession;
function eventsListener(e){
console.info('Change of status|Server response: '+e.type+':'+e.message+':'+e.
session+':'+e.description);
if(e.type == 'started'){
login();
}
else if(e.type == 'i_new_message'){ // incoming new SIP MESSAGE (SMS-like)
acceptMessage(e);
}
else if(e.type == 'i_new_call'){ // incoming audio/video call
if(confirm("Incomming Call Request! Do you accept?")){
acceptCall(e);
}else{
e.newSession.reject()
}
}
else if(e.type == 'connected'){
if(e.session == registerSession){
setStatus(e.type,'Registered...');
}else{
setStatus(e.type,e.description);
}
}
else if(e.type == 'i_ao_request' && e.description == 'Ringing' ){
document.getElementById('call').value = 'End Call';
setStatus(e.type,e.description);
}
else if(e.type == 'terminated' || e.type == 'terminating'){
if(e.session == registerSession){
setStatus('Unable to Register');
}else{
setStatus(e.type,e.description);
}
}
}
function createSipStack(){
sipStack = new SIPml.Stack({
realm: 'foo.bar.com',
impi: 'usertest',
impu: 'sip:usertest#foo.bar.com',
password: '1234',
display_name: 'alice',
websocket_proxy_url: 'ws://11.11.11.0:8080',
enable_rtcweb_breaker: false,
events_listener: { events: '*', listener: eventsListener },
sip_headers: [ // optional
{ name: 'User-Agent', value: 'IM-client/OMA1.0 sipML5-v1.0.0.0' },
{ name: 'Organization', value: 'SuperCops.us' }
]
}
);
}
sipStack.start();
function login(){
registerSession = sipStack.newSession('register', {
events_listener: { events: '*', listener: eventsListener } // optional: '*' means all events
});
registerSession.register();
}
function makeCall(){
var number = document.getElementById('number').value;
if(number == ''){
alert('No number entered');
}
else if(document.getElementById('call').value == 'End Call'){
callSession.hangup();
}else{
setStatus('Trying','Trying to call:'+numberFilter(number));
callSession = sipStack.newSession('call-audio',{
events_listener: { events: '*', listener: eventsListener }
});
callSession.call(numberFilter(number));
}
}
function acceptCall(event){
callSession = event.newSession;
/*('accept',{
events_listener: { events: '*', listener: eventsListener }
});*/
callSession.accept();
eventsListener(callSession);
setStatus('connected','In Call');
}
function setStatus(type,status){
document.getElementById('status').innerHTML = status;
if(type == 'terminated' || type == 'terminating'){
document.getElementById('call').value = 'Call';
}else if(status == 'Ringing' || status == 'Ringing' || status == 'In Call' || type == 'Trying'){
document.getElementById('call').value = 'End Call';
}
}
function numberFilter(number){
return number;
}

How to validate and get form working?

I am trying to validate my form and make it writeToFile when submitted (.txt file) but I can't seem to get it right, searched Google for help but still nothing happens when submit button clicked.
Name:
Business:
Telephone:
Comment:
The Script I tried:
function validateForm()
{
var x=document.forms["commentform"]["fname"]["fcomment"].value;
if (x==null || x=="")
{
alert("You must enter a Name and Comment");
return false;
}
}
if( document.commentform.fname.value == "" )
{
alert("You must enter a Name");
return false;
}
if( document.commentform.fcomment.value == "" )
{
alert("You must enter a Comment");
return false;
}