How to connect Mailchimp subscribers with Firebase using AngularJS - javascript

I have my database with Firebase and now I'm trying to do a newsletter subscription, but I want to save the subscribers in Mailchimp and Firebase.
Mailchimp connection works perfectly, but I don't know how to integrate the Firebase connection in the same js.
This is what I have in the <head> tag
<script type="text/javascript">
angular.module("productLaunch", ["mailchimp"])
</script>
This in the <body> tag
<body ng-app="productLaunch"><section class="container-fluid subscribe" ng-controller="MailchimpSubscriptionCtrl">
<div class="wrapper">
<!-- Let us your email -->
<div class="">
<h2 class="text-center">Subscribe to our news</h2>
<div class="col-lg-4 col-lg-offset-4 mt centered">
<h4 ng-hide="mailchimp.result ==='success'">LET ME KNOW WHEN YOU LAUNCH</h4>
<h4 ng-show="mailchimp.result ==='success'">THANKS FOR SIGNING UP!</h4>
</div>
<form class="form-inline" role="form" ng-hide="mailchimp.result === 'success'">
<input class="hidden" type="hidden" ng-model="mailchimp.username" ng-init="mailchimp.username='stopappweb'">
<input class="hidden" type="hidden" ng-model="mailchimp.dc" ng-init="mailchimp.dc='us12'">
<input class="hidden" type="hidden" ng-model="mailchimp.u" ng-init="mailchimp.u='3eb39be3ad857e60b357fdb5e'">
<input class="hidden" type="hidden" ng-model="mailchimp.id" ng-init="mailchimp.id='520ddfd981'">
<div class="form-group">
<label class="sr-only" for="mailchimp.email">Email address</label>
<input type="email" class="form-control" id="mailchimp.email" placeholder="Enter email" ng-model="mailchimp.email">
</div>
<button type="submit" class="btn btn-info" ng-disabled="MailchimpSubscriptionForm.$invalid" ng-click="addSubscription(mailchimp)" type="submit" value="SIGN UP" disabled="disabled">Submit</button>
<div ng-show="mailchimp.result === 'error'">
<p ng-bind-html="mailchimp.errorMessage" class="error"></p>
</div>
</form>
</div>
</div>
</section>
And this is my JS:
'use strict';
angular.module('mailchimp', ['ng', 'ngResource', 'ngSanitize'])
.controller('MailchimpSubscriptionCtrl', ['$log', '$resource', '$scope',
function ($log, $resource, $scope) {
$scope.myData = new Firebase("https://stopappwebpre.firebaseio.com/subscriptors");
// Handle clicks on the form submission.
$scope.addSubscription = function (mailchimp) {
var actions,
MailChimpSubscription,
params,
url;
$scope.myData.push({mailchimp.email:$scope.mailchimp.email});
// Create a resource for interacting with the MailChimp API
url = 'http://' + mailchimp.username + '.' + mailchimp.dc + '.list-manage.com/subscribe/post-json';
params = {
'EMAIL': mailchimp.email,
'FNAME': mailchimp.fname,
'LNAME': mailchimp.lname,
'c': 'JSON_CALLBACK',
'u': mailchimp.u,
'id': mailchimp.id
};
actions = {
'save': {
method: 'jsonp'
}
};
MailChimpSubscription = $resource(url, params, actions);
// Send subscriber data to MailChimp
MailChimpSubscription.save(
// Successfully sent data to MailChimp.
function (response) {
// Define message containers.
mailchimp.errorMessage = '';
mailchimp.successMessage = '';
// Store the result from MailChimp
mailchimp.result = response.result;
// Mailchimp returned an error.
if (response.result === 'error') {
if (response.msg) {
// Remove error numbers, if any.
var errorMessageParts = response.msg.split(' - ');
if (errorMessageParts.length > 1)
errorMessageParts.shift(); // Remove the error number
mailchimp.errorMessage = errorMessageParts.join(' ');
} else {
mailchimp.errorMessage = 'Sorry! An unknown error occured.';
}
}
// MailChimp returns a success.
else if (response.result === 'success') {
mailchimp.successMessage = response.msg;
}
},
// Error sending data to MailChimp
function (error) {
$log.error('MailChimp Error: %o', error);
}
);
}; }]);
Thank you so much for your help.

Related

Getting a 405 (Method Not Allowed) in AngularJS

So, I am creating a web app, where one page I have a user list and on the second page, I have the users details page. On the second page, I have a confirm button where I want to remove that user when the "Confirm" button is clicked with a 200 Status code. However, I am getting a DELETE : 405 (Method Not Allowed). So, here is my code down below. Please tell me or help me fix this problem. Thank you in advance.
Here is my code.
<div ng-controller="MyCtrl">
<div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">
<a class="back" href="#/lawyer">Back</a>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>
<button class="btn btn-primary" ng-click="doDelete(id)">Confirm</button>
<div class="people-view">
<h2 class="name">{{person.firstName}}</h2>
<h2 class="name">{{person.lastName}}</h2>
<span class="title">{{person.email}}</span>
<span class="date">{{person.website}} </span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.firstName">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.lastName">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
</fieldset>
</form>
</div>
</div>
</div>
Services
app.factory('people', function ($http) {
var service = {};
service.getUserInfo = function () {
return $http.get('https://api-dev.mysite.io/admin/v1/unconfirmed_lawyers');
};
service.confirmUser = function (lawyerId) {
return $http.put('https://api-dev.mysite.io/admin/v1/lawyers/{lawyerId}/confirm');
};
return service;
});
LawyerController
app.controller('LawyerController', ['$scope', 'people', '$routeParams',
function ($scope, people, $routeParams) {
$scope.lawyerId = $routeParams.id;
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
});
}]);
HomeController
var isConfirmed = false;
app.controller('HomeController', function($scope, people, $http) {
if (!isConfirmed) {
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
}, function (error) {
console.log(error)
});
}
});
App.js
$scope.doDelete = function(lawyer) {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
$scope.userInfo.lawyers.splice(index, 1);
location.href = '#/lawyer';
};
If you changed your HTML, so you passed the person instead.
<button class="btn btn-primary" ng-click="doDelete(person)">Confirm</button>
You can use this to find the index within the lawyers, then remove it.
$scope.doDelete = function(lawyer) {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
$scope.userInfo.lawyers.splice(index, 1)
};
The issue is your are using $http.delete which performs an HTTP Delete request. This doesn't sound like something you intended.

AngularJS User Login to Json file

I am currently trying to create a user login page where the user information is stored on a json file. I have created my GET method to the file but I cannot seem to redirect after the user has logged in successfully. Can you help me out?
I know that user login and validation done on the client side is A BAD IDEA but that is how I want to do it, without using a database.
Here is my HTML code:
<body ng-controller="myCtrl">
<form id="login-form">
<h3>User Login</h3>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<button type="submit" class="btn btn-default" id="login-button" ng-click="LogOn()">Login</button>
</form>
</body>
My JavaScript code:
var app = angular.module('myApp', [ ]);
app.controller("myCtrl",['$scope', '$http', function($scope, $http){
$scope.LogOn = function(){
$http.get('data.json').then(function(data){
$scope.users = data;
});
if (data.email == email) && (data.password = password{
window.location.href = 'www.google.com';
}
};
}]);
My JSON File:
[
{
"email":"something#yahoo.com",
"Password":"password"
},
{
"email":"test#yahoo.com",
"password":"test999"
},
{
"email":"xxx#mail.xx",
"password":"xxx"
}
]
Please try to open the link and check and run the code which is deployed in w3 schools
https://www.w3schools.com/code/tryit.asp?filename=FDVZY3NXVYG6
Put redirection code inside then
$http.get('data.json').then(function(data){
$scope.users = data;
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}
});
Obviously the if bellow has to be inside the .then( callback
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}

AngularJS + PHP. Login panel

I have very big problem with login panel. I am still learning AngularJS.
Can you help me with login panel? Here is my code guys. I don't know what I should do now:
api.php:
public function getLogin()
{
$sql = "SELECT login FROM users WHERE login='$username' AND password='$password'";
return $this->db->fetchAll();
}
$app->get('/login', function () use ($app, $DataProvider) {
$login = $DataProvider->getLogin();
return $app->json($login);
});
login.html:
<div class="row">
<div class="col-lg-10 col-sm-10 col-xs-12">
<div class="flat-panel">
<div class="flat-panel-header">
<h3 class="flat-panel-heading">Panel logowania</h3>
</div>
<div class="flat-panel-body">
<div class="form-group">
<input type="text" class="form-control" ng-model="loginInfo.username" placeholder="Podaj login">
</div>
<div class="form-group">
<input type="password" class="form-control" ng-model="loginInfo.password" placeholder="Podaj hasło">
</div>
<div class="form-group">
<button ng-click="loginUser()" class="btn btn-primary">Zaloguj</button>
</div>
</div>
</div>
</div>
</div>
services.js:
app.factory('login', ['$http', function($http){
var _getLogin = function (callback) {
callback = callback||function(){};
$http.get('/api.php/login')
.success(function (data) {
callback(data);
});
};
return {
getLogin: _getLogin
};
app.js:
app.controller("LoginController", function($scope, $http){
$scope.loginInfo = {
username: undefined,
password: undefined
}
$scope.loginUser = function(){
var data = {
username: $scope.loginInfo.username,
password: $scope.loginInfo.password
}
};
})
For angular you need token based authentication.
What is token based authentication?
I never use silex but I found this
https://gonzalo123.com/2014/05/05/token-based-authentication-with-silex-applications/
Another method is normal login form and when user login in see angular app, but this is bad when you try create mobile app.
Take a look at for example this:
https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps
I recommend jwt auth it's very nice!

Can't create a new user on Angular Sign Up page

I am trying to create a new user in Angular. I'm attempting to send a POST request to my api through the client side to create a new user. Unfortunately I can't successfully send the post request. Sending the request through Postman is successful, but not through Angular. Any ideas on what could be the issue? Any help is appreciated.
userCtrl.js
//./public/app/controllers/userCtrl.js
angular.module('userCtrl',['userService'])
//SIGN UP CTRL ================================
//inject the User factory
.controller('userCreateController', function($location, User){
var vm = this;
//Function that creates a new user
vm.saveUser = function(){
//For spinner animation when signing up
vm.processing = true;
//Use the create funciton in the userService
User.create(vm.userData)
.then(function(data){
if(data.success){
$location.path('/login');
}else {
console.log('error');
vm.processing = false;
}
})
}//End saveUser
})//End userCreateController
userService.js
//userService.js
angular.module('userService', [])
.factory('User', function($http){
//create a user factory object
var userFactory = {};
//get a single user
userFactory.get = function(id){
return $http.get('/api/users/' + id);
};
//get all users
userFactory.all = function(){
return $http.get('/api/users/');
};
//create a user
userFactory.create = function(userData){
return $http.post('/api/users/', userData);
};
//update a user
userFactory.update = function(id, userData){
return $http.put('/api/users/' + id, userData);
};
//delete a user
userFactory.delete = function(id){
return $http.delete('/api/users' + id);
};
//return userFactory object
return userFactory;
});
routes.js
//./public/app/routes.js
angular.module('appRoutes', ['ngRoute'])
.config(function($routeProvider, $locationProvider){
$routeProvider
//homepage route
.when('/',{
templateUrl : 'app/views/pages/home.html'
})
.when('/login',{
templateUrl: 'app/views/pages/login.html',
controller: 'mainController',
controllerAs: 'login'
})
.when('/signup',{
templateUrl: 'app/views/pages/signup.html',
controller: 'userCreateController',
controllerAs: 'signup'
})
//Remove hash in the Url
$locationProvider.html5Mode(true);
})//End config
signup.html
<div class="row col-sm-6 col-sm-offset-3">
<div class="jumbtron">
<h1>Sign Up</h1>
<!-- Sign Up Form -->
<form ng-submit='signup.saveUser()'>
<!-- Name Input -->
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Enter Your Name" ng-model='signup.userData.name'>
</div>
<!-- Username Input -->
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" placeholder="Enter Username" ng-model='signup.userData.username'>
</div>
<!-- Password Input -->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" placeholder="Enter Password" ng-model='signup.userData.password'>
</div>
<!-- Signup Button -->
<button type="submit" class="btn btn-block btn-success">
<!-- Show SignUP -->
<span ng-if="!signup.processing">Sign Up</span>
<!-- Show spinner animation when signing up -->
<span ng-if="signup.processing" class="spinner">
<span class="glyphicon glyphicon-repeat"></span>
</span>
</button>
</form>
<!-- End Sign Up Form -->
</div>
</div>
It is difficult to say without more information like the browser console log, but if you are minifying the code, it could be due to the implicit annotation syntax used in the controller injection.
Try to write it with the preferred Inline Array Annotation like:
.controller('userCreateController',
['$location', 'User', function($location, User){
...
}]);
at signup.html you are modifying signup.userData.* but at userCtrl.js you are sending vm.userData instead of $scope.signup.userData.
The problem could be that you are sending an undefined object instead of the userData object.

AngularJS Randomly Finds Module, Randomly does not, Randomly throws Error

I didn't find a case similar to mine, but I'm just learning AngularJS so I probably am missing it. Just slap me upside the head and point me in the right direction if this was already a question. Anyways...
I made an Add User form for the work study site that I am working on, and I used AngularJS to do so. When it finds the module, it works swimmingly. Unfortunately, it finds it maybe one out of 5 times. 3 out of 5 times, I get absolutely nothing in the console. 1 out of 5 times, though, I get an AngularJS error.
Failed to instantiate module addUser due to:
Error: [$injector:nomod] http://errors.angularjs.org/1.4.1/$injector/nomod?p0=addUser
at Error (native)
at http://localhost/kushal/html/body/angular.min.js:6:416
at http://localhost/kushal/html/body/angular.min.js:23:433
at a (http://localhost/kushal/html/body/angular.min.js:22:483)
at Q.bootstrap (http://localhost/kushal/html/body/angular.min.js:23:218)
at http://localhost/kushal/html/body/angular.min.js:37:314
at n (http://localhost/kushal/html/body/angular.min.js:7:322)
at g (http://localhost/kushal/html/body/angular.min.js:37:92)
at db (http://localhost/kushal/html/body/angular.min.js:40:367)
at d (http://localhost/kushal/html/body/angular.min.js:19:219
I read that maybe I am using a property in my module that is not supported, but I don't know which that would be. My add_user.js file is as follows:
$(document).ready(function() {
(function() {
var AddApp = angular.module('addUser', ['ngSanitize']);
AddApp.controller('AddUserController', ['$http', '$scope', function($http, $scope){
$scope.SchoolSelBox = null;
$scope.schoolList = [];
$scope.CitySelBox = null;
$scope.cityList = [];
$scope.StateSelBox = null;
$scope.stateList = [];
$scope.TypeSelBox = null;
$scope.typeList = [];
$scope.master = {};
var original = $scope.user;
$http.post("lib/scripts/adding_user.php", {switch_id: '1', func: 'retrieve_schools'}).
success(function(data) {
$scope.schoolList = data;
console.log(data);
}).
error(function(data, status, headers, config) {
console.log(data, status, headers, config);
});
$http.post("lib/scripts/adding_user.php", {switch_id: '1', func: 'retrieve_cities'}).
success(function(data) {
$scope.cityList = data;
}).
error(function(data, status, headers, config) {
console.log(data, status, headers, config);
});
$http.post("lib/scripts/adding_user.php", {switch_id: '1', func: 'retrieve_states'}).
success(function(data) {
$scope.stateList = data;
}).
error(function(data, status, headers, config) {
console.log(data, status, headers, config);
});
$http.post("lib/scripts/adding_user.php", {switch_id: '1', func: 'retrieve_account_types'}).
success(function(data) {
$scope.typeList = data;
}).
error(function(data, status, headers, config) {
console.log(data, status, headers, config);
});
$scope.addUser = function(user) {
$scope.master = angular.copy(user);
console.log($scope.master);
$http.post("lib/scripts/adding_user.php", {
switch_id: '1',
func: 'authenticate_user',
username: $scope.master.username,
email: $scope.master.email,
first: $scope.master.FName,
last: $scope.master.LName,
school: $scope.master.SchoolSelBox['school_id'],
city: $scope.master.CitySelBox['city_id'],
state: $scope.master.StateSelBox['state_id'],
account_type: $scope.master.TypeSelBox['security_level_id']
}).
success(function(response){
console.log(response);
if (response.length > 1) {
alert('An has error occured. Please contact an administrator at stem.admin#minotstateu.edu.'); //An error not caught below
} else {
var responseArray = response.split('');
for (var x = 0; x < responseArray.length; x++) {
switch (responseArray[x]) {
case "1":
$("#username_error").text("Username Already Taken");
break;
case "2":
$("#email_error").text("*");
$("#input_error").css("color", "#FF0000");
$("#input_error").text("An account is already registered for this email");
break;
case "3":
$("#input_error").css("color", "#6d962f");
$("#input_error").text("Account Successfully Added");
$scope.user = angular.copy(original);
$scope.addUserForm.$setPristine();
break;
case "4":
$("#input_error").css("color", "#FF0000");
$("#input_error").text("Account could not be added"); //PHP error
break;
default:
alert("add_user.js, add_user()"); //Not real sure what this does
break;
}
}
}
}).
error(function(data, status, headers, config) {
console.log(data, status, headers, config);
});
};
$scope.resetFrm = function() {
$scope.user = angular.copy(original);
$scope.addUserForm.$setPristine();
$("#username_error").text("");
$("#email_error").text("");
$("#input_error").text("");
};
}]);
})();
});
I don't know if you will need the HTML for this or not, so here is add_user.php:
<?php
session_start();
if (($_SESSION['sec_level']) != 4) {
header("Location: permission_error.php");
}
include "lib/header/header.php";
include "lib/linklib.php";
?>
<!DOCTYPE html>
<html ng-app="addUser">
<head>
<title>Add User</title>
<?php
csslib();
jslib();
?>
<script type="text/javascript" src="lib/js/add_user.js"></script>
</head>
<body >
<center><div id="bordercontainer">
<?php
headermenu();
?>
<div id="maincontainer">
<br />
<span class="header headerTextAlignment">Add User</span>
<br />
<center>
<br />
<div id="addusercontainer">
<form name="addUserForm" novalidate ng-controller="AddUserController as addUserCtrl" ng-submit="addUserForm.$valid && addUser(user)">
<!--Checks to see if the form is valid before submission using the $valid form controller. AND statement. ng = Angular JS -->
<div class="row-fluid">
<span class="adduser_heading">Username:</span>
<input type="text" id="username" class="adduser_input" size="35" ng-model="user.username" required ng-pattern="string"/>
<span class="adduser_error" id="username_error"></span>
</div>
<div class="row-fluid">
<span class="adduser_heading">Email:</span>
<input type="email" name="email" id="email" class="adduser_input" size="35" ng-model="user.email" required ng-pattern="string"/>
<span class="adduser_error" id="email_error"></span>
</div>
<div class="row-fluid">
<span class="adduser_heading">Confirm Email:</span>
<input type="email" name="email" id="confirm_email" class="adduser_input" size="35" ng-model="user.ConfEmail" required ng-pattern="string"/>
<span class="adduser_error" id="match_error"></span>
</div>
<div class="row-fluid">
<span class="adduser_heading">First Name:</span>
<input type="text" id="first" class="adduser_input" size="35" ng-model="user.FName" required ng-pattern="string"/>
<span class="adduser_error" id="first_error"></span>
</div>
<div class="row-fluid">
<span class="adduser_heading">Last name:</span>
<input type="text" id="last" class="adduser_input" size="35" ng-model="user.LName" required ng-pattern="string"/>
<span class="adduser_error" id="last_error"></span>
</div>
<div class="row-fluid">
<span class="adduser_heading">School:</span>
<select ng-model="user.SchoolSelBox" ng-options="name.school_name for (key, name) in schoolList" id="school" class="adduser_input" style="width: 264px;" required></select>
</div>
<div class="row-fluid">
<span class="adduser_heading">City:</span>
<select ng-model="user.CitySelBox" id="city" class="adduser_input" style="width: 264px;" ng-options="name.city_name for (key, name) in cityList" required></select>
</div>
<div class="row-fluid">
<span class="adduser_heading">States:</span>
<select ng-model="user.StateSelBox" id="state" class="adduser_input" style="width: 264px;" ng-options="name.state_name for (key, name) in stateList" required></select>
</div>
<div class="row-fluid">
<span class="adduser_heading">Account Type:</span>
<select ng-model="user.TypeSelBox" id="account_type" class="adduser_input" style="width: 264px;" ng-options="name.security_level_type for (key, name) in typeList" required></select>
</div>
<div class="row-fluid">
<div class="adduser_button_left">
<button class="btn btn-primary" type="reset" id="reset" value="Reset" >Reset</button>
</div>
<span class="adduser_large_error" id="input_error"></span>
<div class="adduser_button_right">
<button type="submit" class="btn btn-primary" id="submit" value="Submit" >Submit</button>
</div>
</div>
</form>
</div>
<br />
</center>
<!-- Load Modal -->
<div id="loadModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-body">
<div class="progress">
<div class="bar" style="width: 0%; " data-percentage="100" ></div>
</div>
<span id="comment"></span>
</div>
</div>
</div>
</div>
</body>
</html>
I do have Angular JS and ngSanitize included in that lib/linklib.php file. All those console.log()'s are there for feedback. The JS goes to PHP back-end code which interacts with the database. If you need any more information, I will try and get it up asap. Just a bit stumped since it seems to be happening 1/5 times.
Oh, this is through localhost. I have my own copy of the code and the database, so I am not going through a firewall or gateway or anything like that to access the database. Don't know if that matters, just tossing it out there.
Thanks.
Edit: Should probably mention what happens when it does not work. The HTML loads just fine, but the select boxes do not populate. Clicking the Submit and Reset button don't do anything.
I removed the jQuery $(document).ready, as per o4ohel's suggesstion, and it works swimmingly and consistently now. Thanks!

Categories