AngularJS post Data to nodeJs/Sequelize - javascript

I am creating an e-commerce web site with Nodejs/Sequelize and AngularJs.
I am actually got this starter AngularJS starter.
In my project I got 2 folders :
Client (which contains AngularJS starter folders)
Server (which contains my server.js
I would like to register a user, I got my "registeredView.html" with a form :
<form ng-submit="submit()">
<input type="text" name=firstname ng-model="user.firstname" placeholder="firstname" required=" ">
<input type="text" name="lastname" ng-model="user.lastname" placeholder="lastname" required=" ">
<input type="email" name="email" ng-model="user.email" placeholder="Email Address" required=" ">
<input type="password" name="password" ng-model="user.password" placeholder="Password" required=" ">
<input type="password" name="confirm_password" ng-model="user.confirm_password" placeholder="Password Confirmation" required=" ">
<input type="submit" value="Register">
</form>
For now, I could get those datas in my "RegisteredController" thanks to the $scope.user but I don't know how to send those data to my server.
I am using express module so I tried with $http.post like this :
.controller('RegisteredController', ['$scope', function ($scope, $http) {
$scope.submit = function () {
$http.post('/registered', $scope.user)
then(function (response) {
console.log("posted")
}).catch(function (response) {
console.error(response)
})
}
}]);
And on my "server.js" I tried to get this post like this :
app.get('/registered', function (req, res) {
console.log(req.body)
res.end();
});
But it dont works..
What I wrong ? Some Advice ?
I need your helps guys please :)

As discussed in the comments there are 3 immediately apparent issues:
Your server is expecting a get, not a post, change app.get('/registered'...) to app.post('/registered'...).
You're missing a dot here: $http.post('/registered', $scope.user)then(function (response) {, between the closing ) and then.
You need to mark your $http to be injected, as with $scope - change ['$scope', function ($scope, $http) to ['$scope', '$http', function ($scope, $http).
To be able to do something with your posted data you should check out body parser. After requiring it you can do the following - app.use(bodyParser.json()). Then you should have access to req.body which should contain your user parsed as a javascript object.

Related

AngularJs scope params undefined [duplicate]

This question already has answers here:
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
(3 answers)
Closed 4 years ago.
I have just started learning AngularJS and I am trying to make this simple app with simple inputs, controllers and a firebase database.
Problem is, the $scope params userEmail and userPassword are always undefined in Signin() when I click the button.
HTML relevant code:
<body ng-app="indexApp">
...
<div class="row" ng-controller="loginCtrl">
<div class="hero-text-box">
<br>
<form>
<p class="p2"><label for="email">email</label></p>
<input ng-model="userEmail" id="email1" type="email"
name="email1" placeholder="email">
<p class="p2"><label for="password">pasword</label></p>
<input ng-model="userPassword" type="password" id="password"
name="password" placeholder="password" required>
<a class="btn btn-full" href="#" ng-click="Signin()">הכנס</a>
</form>
</div>
</div>
AngularJS javascript code:
var app = angular.module("indexApp", ["firebase"]); // using firebase
app.controller("loginCtrl", function($scope, $firebaseArray) // AngularJS
will auto add firebase
{
var ref = firebase.database().ref().child("users")
// create a synchronized array
$scope.users = $firebaseArray(ref)
$scope.Signin = function()
{
console.log($scope.userEmail) -- undefined!
....
If you want to use form with angularJS, you should follow angularjs form guide:https://docs.angularjs.org/guide/forms
In your case, you need to move signin() function to html form element.I created a jsfiddle based on your code: http://jsfiddle.net/sxwei123/ADukg/25254/
Hope this would help!
This might help
HTML
<body ng-app="indexApp">
...
<div class="row" ng-controller="loginCtrl">
<div class="hero-text-box">
<br>
<form>
<p class="p2"><label for="email">email</label></p>
<input ng-model="userdata.userEmail" id="email1" type="email"
name="email1" placeholder="email">
<p class="p2"><label for="password">pasword</label></p>
<input ng-model="userdata.userPassword" type="password" id="password"
name="password" placeholder="password" required>
<a class="btn btn-full" href="#" ng-click="Signin(userdata)">הכנס</a>
</form>
</div>
</div>
Controller
var app = angular.module("indexApp", ["firebase"]); // using firebase
app.controller("loginCtrl", function($scope, $firebaseArray) // AngularJS
will auto add firebase
{
var ref = firebase.database().ref().child("users")
// create a synchronized array
$scope.users = $firebaseArray(ref)
$scope.userdata = {};
$scope.Signin = function(data){
console.log(data) // you will get the object
}

Convert HTML form into Angular POST request

I have this form in HTML and I am trying to convert it into a POST request using a frontend framework (either AngularJS or Angular2). The purpose of this form is to allow a client to subscribe to my wordpress blog. I am trying to convert it from PHP to Angular2 (if someone knows how to convert it to AngularJS I can convert to Angular2 from there). How would I do this? What would have to be in the body of the POST request vs query strings? I am having trouble understanding exactly what role each part of this form plays in the POST request.
EDIT: Just to clarify, I know how to use AngularJS and Angular2 and how to use the HTTP service in both of them. I am wondering how to convert the form into the body/query strings of the request.
<form action="/blog/" class="form-inline" role="form" method="POST" accept-charset="utf-8" id="subscribe-blog">
<!-- add hidden inputs for wordpress jetpack widget -->
<input type="hidden" name="action" value="subscribe" />
<input type="hidden" name="source" value="http://www.mywebsite.com/blog/" />
<input type="hidden" name="sub-type" value="widget" />
<input type="hidden" name="redirect_fragment" value="blog_subscription-2" />
<label class="sr-only" for="exampleInputEmail">Email address</label>
<input type="email" class="form-control wide" id="exampleInputEmail" placeholder="Enter email address">
<button type="submit" name="jetpack_subscriptions_widget" class="btn btn-submit">Subscribe</button>
</form>
Would something along the lines of this be correct?
postForm() {
var body = {
action: 'subscribe',
source: 'http://www.mywebsite.com/blog/',
sub-type: 'widget',
redirect_fragment: 'blog_subscription-2',
email: 'clientEmailAddress#gmail.com', // don't think this is right
// not sure what to do with `jetpack_subscriptions_widget` attribute on the submit button either
};
return this.http.post(`http://www.mywebsite.com/blog/`, body)
.map(res => res.json())
.toPromise()
.then(data => {
return data;
});
}
You need to include angular.min.js and script.js
html
<body ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="name" />
<input type="submit" value="Send" ng-click="send(name)"/>
</body>
angular js code:
script.js
angular.module('myApp', [])
.controller('myCtrl', ['$scope', '$http', funtion($scope, $http){
$scope.name = ""; // intially the input field is empty. As you type in the input field, the value will be updated here.
$scope.send = function(name){
alert(name);
var url = $scope.name; // try to enter an url
$http.get(url).then(function Success(res){
// here you can do anything with res
}, function Error(err){
alert(error);
})
}
}]);
Using angular, you split the application in parts:
view (html)
process some validations, etc (controller)
and do some model logic processing (service).
If you want to make the http request completely with angular to an endpoint (backend service, REST, or any other), usually in this case:
You use ng-model for each input field you need to send in the request, something like <input type="text" ng-model="val">. In your case your html would be something like:
html
<form ng-submit="send()" class="form-inline" role="form" accept-charset="utf-8" id="subscribe-blog">
<!--no need of 'action' attribute in the form since the post will be done using angular-->
<!-- add hidden inputs for wordpress jetpack widget -->
<input type="hidden" name="action" value="subscribe" ng-model="subscribe"/>
<input type="hidden" name="source" value="http://www.mywebsite.com/blog/" ng-model="source"/>
<input type="hidden" name="sub-type" value="widget" ng-model="widget" />
<input type="hidden" name="redirect_fragment" value="blog_subscription-2" ng-model="redirect_fragment"/>
<label class="sr-only" for="exampleInputEmail">Email address</label>
<input type="email" class="form-control wide" id="exampleInputEmail" placeholder="Enter email address" ng-model="email">
<button type="submit" name="jetpack_subscriptions_widget" class="btn btn-submit">Subscribe</button>
</form>
Then in your controller you can process all your ng-model if needed and then pass those values to a (angular) service like this
//....angular controller
function send(){
//..collect params using the ng-models
var params = [];
params['email'] = $scope.email; //here you define 'email' as the name of the param received by the webservice as input !!!
myService.sendValues(params).then(function(data){
})
}
...where you would finally send the values to the php service like code below:
//... angular service
function sendValues(params){
var url = "miendpointurl/subscribe";
//... at this pont in params you have all those params you named like 'email', 'subscribe' and so on
return $http.post(url, params).then(function(response){
return response.data;
},
function(responseOnError){
return responseOnError.data;
}
}
Angular will interact with the php service transparently to you and will give you back the server response.

I can't access ng-model from a controller [AngularJS]

I'm developing an e-commerce site for learnign purposes.
HTML:
<div class="container">
<form class="log-in-form" ng-controller="ControllerLogin">
<div class="form-group">
<label for="loginEmail">Email address</label>
<input type="email" class="form-control" id="loginEmail" placeholder="Email" ng-model="email">
</div>
<div class="form-group">
<label for="loginPass">Password</label>
<input type="password" class="form-control" id="loginPass" placeholder="Password" ng-model="password">
</div>
<button class="btn btn-default" ng-click="authenticate()">Login</button>
</form>
</div>
Angular javascript
app.controller('ControllerLogin', ['$scope', '$http', 'ServiceLogin', function ($scope, $http, ServiceLogin) {
$scope.authenticate = function () {
console.log($scope.email);
ServiceLogin.auth($scope.email, $scope.password)
.success(function (data) {
alert(data);
});
}
}]);
Every time I console.log the $scope.email, or password. It throws an error of undefined. I'm just starting on angular and I don't know why is not getting the models, I thinks my code is correct. Any help you can give I will be gratefull.
From Angular site:
Note that novalidate is used to disable browser's native form validation.
The value of ngModel won't be set unless it passes validation for the input field. For example: inputs of type email must have a value in the form of user#domain.
Reference: https://docs.angularjs.org/guide/forms
So the reason it may be blank is that it's not a valid email.
You can look at their demo for the email type and see it in action.
I recommend adding:
{{email}}
<br>
{{password}}
somewhere in your html within the controller's HTML scope for your own debugging.
Good luck.

POST is not getting current values from angular

In my view there are two forms (one is visible, second one is hidden). First one as action calls submit1() function in controller, that in turn will invoke document.getElementById('form2').submit(); Second form action has method POST that directly calls php.
Now I cannot get why if my submit1() looks like this:
function submit1()
{
// doesnt matter
$scope.first = 'this is my string'; // here I'm modifying variable from $scope1 that is directly in form2
document.getElementById('form2').submit(); // problem here!
// doesn't matter
}
It does not work as expected.
Basically, when form2 is sent, it still has a default value (not changed one).
Looks like it would not really change variable outside the scope of function submit1() or like POST would not accept this change. Anyone can tell me why it is like that?
Moreover I was previously using $http post method instead document.getElement().submit() and it works fine. So this seems to be weird.
I would appreciate any help in this matter.
Thank you!
Edit1: (adding more code to properly define what is a problem):
view:
<div class="container">
<div ng-hide="true" >
<form action="./order2.php" id="form2" method="POST">
<input type="text" name="username" value="{{username}}"/>
<input type="text" name="phone" value="{{phone}}"/>
<input type="text" name="address" value="{{address}}"/>
<input type="text" name="price" value="{{totalPrice}}"/>
<input type="text" name="email" value="{{email}}"/>
<input type="text" name="message" value="{{text}}"/>
<input type="submit"/>
</form>
</div>
<form novalidate id="contact-form" name="contactForm">
<a class="btn btn-success" ng-click="submit1()" href>
<i class="fa fa-check-circle-o fa-lg"></i>
{{ 'ID_ORDER_BUTTON' | translate:$root.currentLang }}
</a>
</form>
</div>
Controller:
Appcontrollers.controller('controller1', function($scope, $http, $rootScope, $timeout, $routeParams, $window, $location, databaseService, translationService, cartService, leatherService, $location) {
$scope.text="";
$scope.email="11111#2222.com";
$scope.price=0;
$scope.address= "add";
$scope.phone="1213131";
$scope.username="usera";
$scope.submit1 = function() {
$scope.price=999999999; // this looks like doesn't have effect.
document.getElementById('form2').submit();
}
}

Take string from input and make an AJAX request in AngularJS

Here is my code :
http://jsfiddle.net/n8t2born/1/
there are 3 js files , and it works pretty much good when I use static URL (without inputCity variable inside) . How should I tell angular correctly to take that info from my input and put it into the link and show weather info for a particular city ?
This is my form:
<form class="form-container" ng-submit="Weather.getWeather(inputCity)">
<input class="input-field" type="text" ng-model="inputCity" placeholder="City">
<input class="button-style" type="submit" value="Show Weather">
</form>
and it is my angular.factory:
angular
.module('weather.factory', [])
.factory('Weather', [
'$http',
function($http) {
return {
getWeather : function(inputCity) {
return $http({
url: 'http://api.wunderground.com/api/KEY/conditions/q/' + inputCity + '.json',
method: 'GET'
})
}
}
}
]);
You should never call you service method from your controller which has promise, It should call from controller & then update you required location data in ajax sucess
HTML
<form class="form-container" ng-submit="submitForm(inputCity)">
<input class="input-field" type="text" ng-model="inputCity" placeholder="City">
<input class="button-style" type="submit" value="Show Weather">
</form>
Code
$scope.submitForm =function(inputCity){
Weather.getWeather(inputCity).success(function(){
//data updation will lie here
}).error(function(error){
//do error handling here
})
};

Categories