Parsing problems during JSON response using AngularJS - javascript

I am new using Angularjs and I am having an issue parsing a JSON response. I have login credentials like Username and password and I am trying to parse it , when user clicks on the login button(). If the name and password matched in the following server , I should get success message. This is the HTML code I am using:
<form ng-submit="loginform()" name="logform"><br/><br>
<tr ng-repeat="logcred in signinfo"></tr>
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username" >
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<a ng-click="reloadPage()" class="navbar-brand" ></a>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="submit()" >Login</button>
</div>
</form>
This is the Javascript code using AngularJS:
app.controller('credientials', function($scope,$http) {
$scope.loginform = function (username, password){
$http.get('http://localhost:3000/loginfo')
.then(
function successCallback(data){
$scope.response = data;
if($scope.username === 'response.username' && $scope.password === 'response.password'){
$scope.signinfo = data.loginfo;
}
else{
console.log("Error");
}
})
});
The HTML is showing the variable $scope.response with the JSON returned by the server, but I don't know how to authentication it properly.
What am I doing wrong?
Any help / advice would be greatly appreciated.

EDIT
Check updated snippet of authentication at client side.
if(userData.username == response.data.username && userData.password === response.data.password){
$scope.signinfo = response.data
}
You will get userData variable from form submit button .. see how i am passing
username and pasword to controller using ng-submit="loginform(logcred)"
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
$scope.loginform = function(userData) {
console.log(userData);
$http.post('https://reqres.in/api/users', userData) // here in post rew i am passing username and password to mock api
.then(function(response) {
//as suggested by you in response u will get username = admin#evol.com password = admin;
console.log(response)
if(userData.username == response.data.username && userData.password === response.data.password){
$scope.signinfo = response.data
}
});
}
});
//**NOTE** in above HTTP call you use your url `http://localhost:3000/loginfo` and in your serverside get the username from the request and check password for that username in your database. If password matches with what you have entered then send success message or user details back to client side.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="credientials">
<form ng-submit="loginform(logcred)" name="logform">
<br/>
<br>
{{signinfo}}
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username">
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<a ng-click="reloadPage()" class="navbar-brand"></a>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary">Login</button>
</div>
</form>
</div>
in above HTTP call you use your url http://localhost:3000/loginfo and in your serverside get the username from the request and check password for that username in your database. If password matches with what you have entered then send success message or user details back to client side.
where should i apply if condition, to match the usercredentials?
You need to check if condition in the server side logic where u fetch data from database. like in your server (i.e. in /loginfo)
if(userpassword == passwordfromDB){
//send success message to client side
}

Related

How to submit form and have data stay in input field? Using AJAX and nodejs

I am trying to create a user settings page where a user inputs his/her information, clicks "save", then the page saves the data without clearing the inputted fields or reloading the page. The best example I can think of is the user account settings page on Udemy.
A LOT of the similar questions I've looked at are using php or renders data in a div below the form. I want the data to remain IN the form inputs. I'm using nodejs, express, bodyparser.
<form id="updateAccSettings" action="/account" method="POST">
<div class="form-group">
<label for="address">Address* </label>
<input class="form-control" type="text" name="address" placeholder="Address" required/>
</div>
<div class="form-group">
<label for="address2">Address 2 </label>
<input class="form-control" type="text" name="address2" placeholder=""/>
</div>
<div class="form-group">
<label for="city">City* </label>
<input class="form-control" type="text" name="city" placeholder="City" />
</div>
<div class="form-group">
<input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
</div>
</form>
I've tried this with AJAX
$(document).ready(function() {
$("#updateAccSettings").on("submit", function(e){
e.preventDefault();
var details = $("#updateAccSettings").serialize();
$.post("/account", details, function(data){
$("#updateAccSettings").html(data);
});
});
});
and this
$(document).ready(function () {
$("#updateAccSettings").bind("submit", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/account",
data: $("#updateAccSettings").serialize(),
success: function(){
alert("You've successfully updated your account settings.")
}
});
});
});
And I have this for my app.js
app.post("/account", function(req, res) {
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = {address: address, address2: address2, city: city};
account.push(updateAccount);
console.log("Updated data");
res.redirect("/settings/account");
});
When I clicked save, I get a Cannot read property of 'push' undefined. I tried deleting the var address, var address2, etc and keeping only the console.log which logs whenever I click save but doesn't keep the data in the input. I tried adding onsubmit="return false" as an attribute on the form tag but the console.log doesn't run when I click save so I assume it's not doing anything with the data.
Not sure how to proceed from here. All my other forms use modals or render results in another page.
You're getting the error because you're trying to push onto an undefined variable. Namely in the last section when posted this app.post:
app.post("/account", function(req, res) {
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = {address: address, address2: address2, city: city};
account.push(updateAccount); // error is being thrown here
console.log("Updated data");
res.redirect("/settings/account");
});
Once you have a dummy variable for account, you can send back to the frontend a json response to be read in the form success handler.
Example code: (I haven't tested it)
Backend:
app.post("/account", function(req, res) {
var account = [];
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = { address, address2, city };
account.push(updateAccount); // error is being thrown here
console.log("Updated data");
res.json(updateAccount);
});
Frontend:
$(document).ready(function () {
$("#updateAccSettings").bind("submit", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/account",
data: $("#updateAccSettings").serialize(),
success: function(data){
$('#address').value(data.address);
$('#address2').value(data.address2);
$('#city').value(data.city);
}
});
});
});
You could give each of your form input fields an id (e.g the same as their "name" property)and get their values individually when doing the ajax request as follows (that way you can reinsert the values after the form is submitted):
HTML
<form id="updateAccSettings" action="" method="POST">
<div class="form-group">
<label for="address">Address* </label>
<input class="form-control" type="text" name="address" id="address" placeholder="Address" required/>
</div>
<div class="form-group">
<label for="address2">Address 2 </label>
<input class="form-control" type="text" name="address2" id="address2" placeholder=""/>
</div>
<div class="form-group">
<label for="city">City* </label>
<input class="form-control" type="text" name="city" id="city" placeholder="City" />
</div>
<div class="form-group">
<input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
</div>
</form>
JQuery
$(document).ready(function() {
$("#updateAccSettings").on("submit", function(e){
e.preventDefault();
//get the values of our input fields and store them in local variables
var address = $("#address").val();
var address2 = $("#address2").val();
var city = $("#city").val();
//prepare the data object to send in the ajax request
var params = {"address": address, "address2": address2, "city" : city};
$.ajax({
type: "POST",
url: "/account",
data: JSON.stringify(params),
dataType: "json",
success: function(data){
//the ajax request was successful
//We can do something with the data we get back here.
//Also we can reinsert the values (that were submitted) to the form
$("#address").val(address);
$("#address2").val(address2);
$("#city").val(city);
},
error: function(xhr, status, error) {
//an error occured in the request so handle it here
}
});
});
});

Trouble creating Stripe Token: 402 (Payment Required) error

Good day everyone,
Below is the error code that is thrown in console:
(index):3 POST https://api.stripe.com/v1/tokens 402 (Payment Required)
(index):3 POST https://api.stripe.com/v1/tokens 402 (Payment Required)c # (index):3e # (index):3a # (index):3Stripe.isDoubleLoaded.Stripe.xhr # (index):3Stripe.a._rawRequest # (index):2Stripe.a.request # (index):2Stripe.token.a.create # (index):2Stripe.card.b.createToken # (index):2Stripe.a._channelListener # (index):2incoming # (index):2f # (index):2
Below is the javascript code
// Generate the user token
$(function() {
// Once the user has submited the form
$(".submit").click(function(e) {
// Prevent the form from submiting by default
e.preventDefault();
// Ensure that checkbox is checked
if($('#checkbox').is(":checked")) {
// Prevent the form from submiting by default
var $form = $('#payment-form');
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
}
else {
// Display an error message to the user by writting directly into the header error tag
document.getElementById('checkboxError').innerHTML = "You must kindly accept the terms and conditions to continue.";
}
});
// Ensure that checkbox is checked
if($('#checkbox').is(":checked")) {
var appendedStripeToken = false;
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Scroll to the billing section
$("#billingError").scrollTop();
// Show the errors on the form:
$form.find('.payment-errors').text(response.error.message);
$form.find('.submit').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
handleCall(token);
}
// What to do after the token has been generated.
function handleCall(token) {
var $form = $('#payment-form');
if (!appendedStripeToken) {
// Insert the token into the form so it gets submitted to the server
appendedStripeToken = true;
phpCall();
}
}
// Post the package name, the token, and the user name information to the billing.php page
function phpCall() {
if( appendedStripeToken === true ){
$.ajax({
type: "POST",
data: {run: true, packageName: $('#packageName').val(), token: token, userName: $('#userName').val(),customerName: $('#customerName').val() },
url: '/app/functions/billing.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
$('#payment-form').prop('disabled', true); // TODO: give your html-submit-input-tag an "id" attribute
window.location = response;
}
});
}
}
}
}
});
Below is the HTML code
<!-- Package name to be submitted to server -->
<input type="hidden" id="packageName" value="{{ packageName|capitalize }}">
<!-- Username to be submitted to server -->
<input type="hidden" id="userName" value="{{ userName }}">
<input type="hidden" id="customerName" value="{{ customerName }}">
<div class="form-row">
<label for="cardHolder">Cardholder Name</label><br>
<input type="text" id="cardHolder" size="20" data-stripe="name">
</label>
</div>
<br><br>
<div class="form-row">
<label for="cardNumber">Card Number </label><br>
<input type="text" id="cardNumber" size="20" data-stripe="number">
</label>
</div>
<br>
<img src="/public/images/credit-card/visa.png" class="card-visa">
<img src="/public/images/credit-card/mastercard.png" class="card-mastercard">
<img src="/public/images/credit-card/american-express.png" class="card-aexpress">
<br>
<div class="form-row">
<label for="cardExpiration"> Expiration (MM/YY)</label><br>
<input class="expirationNumber" type="text" size="2" id="cardExpiration" data-stripe="exp_month">
</label>
<span> / </span>
<input class="expirationNumber" type="text" size="2" data-stripe="exp_year">
</div>
<br><br>
<div class="form-row">
<label for="cardCVC">CVC</label><br>
<input type="text" id="cardCVC" size="4" data-stripe="cvc">
</label>
</div>
</div>
</div>
<input type="checkbox" id="checkbox">
<label for="checkbox">By purchasing this package you are agreeing to our Terms & Conditions</label><br><br>
<h4 id="checkboxError"></h4>
<button type="submit" class="submit btn-tangerine">Submit Payment</button>
</form>
Any help would be greatly appreciated!
I thnk that the main error lies in the following line:
Stripe.card.createToken($form, stripeResponseHandler);
What is suppose to happen is really simple. Token gets created when all proper information are given, and then the token along with other information are posted via ajax to the server where a PHP code will create the charge using these information.
I was facing same issue when I add test API KEYS for payment, then site was working fine and when I add live key then site shows same error on console.
But problem was, I was testing live key with test credit card number. May be you were doing same mistake
And sorry for bad English.

HTTP put is not saving data to the server api using angular

I ma trying to update data in the server using restful api. when i click save buttion . I get the massage that data is updated successfully but It is not saving updating data to the server.
I am passing the function updateop to update the data in the server using ng-submit
<tbody><tr ng-repeat="user in names | filter:filters.search| filter: filters.searchdd | filter:customFilter(unit)">
<td>
{{ user.name }}
<div ng-show="collapsed">
<form name="unitUpdateForm" ng-submit="updateop(user)">
<!-- Name -->
<fieldset class="form-group">
<!-- Name -->
<label >Name</label>
<input ng-model="user.name" placeholder="Name" class="form-control" />
<!-- TODO: Add more attributes -->
<label >Short name</label>
<input ng-model="user.shortName" placeholder="Short name" class="form-control" />
<fieldset class="form-group">
<input type="submit" class="btn btn-primary pull-right"
value="Save" />
</fieldset>
</form>
</div>
</div>
Here is my angular js file where i am calling the function.
$scope.updateop = function(user) {
var apiUrl = "http://localhost:8080/api/organisationUnits/";
console.log(user);
// Setup request
var request = $http({
method: "put",
url: apiUrl + user.id + '.json',
data: user,
});
// Perform request
request.success(function(data) {
// TODO: Some kind of feedback? Angular automatically updates template.
//alert("Update success!");
console.log(data);
//Refreshes the data from db with the newly updated unit
init();
}).error(function(data, status) {
alert("Update error");
init();
});
};
It give me alert update sucess . It is not Updating Data on the server.

Django JQuery AJAX submit form POST request refreshes the page

I have a login form for which I want the client to send AJAX POST request as below with error handling. In case of validation/authentication errors, I don't the page to be reloaded or refreshed to the url corresponding to POST request Handler(/users/login/) with the JSON string received from login view's response. I tried using event.preventDefault() as suggested by many answer on SO but could not make it work. Any clue as to what is going wrong here? I don't think this to be a Django issue. I know that the onsubmit is triggerred because the window redirects to the POST handler URL /users/login/ with the expected JSON string response - {"error": ["Entered mobile number is not registered"]}
JQuery code
$("#loginform").on('submit', function(event) {
event.preventDefault();
alert("Was preventDefault() called: " + event.isDefaultPrevented());
console.log("form submitted!");
var url = "/users/login/";
$.ajax({
type: "POST",
url:url,
data: $("#loginform").serialize(),
success: function(data)
{
console.log(data);
var result = JSON.stringify(data);
if(result.indexOf('errors')!=-1 ){
console.log(data);
if(data.errors[0] == "Mobile number and password don't match")
{
$('.login-error').text("Mobile number and password don't match");
}
else if(data.errors[0] == "Entered mobile number is not registered")
{
$('.login-error').text("Entered mobile number is not registered");
}
}
else
{
window.open("/users/profile/");
}
//var result = JSON.stringify(data);
// console.log(result);
}
})
});
View Handler
def login(request):
if request.method == 'POST':
mobile_number = request.POST.get('mobile_number', '')
password = request.POST.get('password', '')
data = {}
user_queryset = User.objects.filter(mobile_number=mobile_number)
if len(user_queryset) == 0:
data['error'] = []
data['error'].append("Entered mobile number is not registered")
# return JsonResponse(data)
elif len(user_queryset) == 1:
email = user_queryset[0].email
user = auth.authenticate(email=email, password=password)
if user is not None:
auth.login(request, user)
else:
data['error'] = []
data['error'].append("Mobile number and password don't match")
return JsonResponse(data)
HTML code
<div class="container-fluid bg-primary" id="login">
<div class="row">
<div class="col-lg-3 text-center">
</div>
<div class="col-lg-6 text-center">
<h1> </h1><h3> </h3>
<h2 class="section-heading">Login to your profile</h2>
<hr>
</div>
<div class="col-lg-3 text-center">
</div>
<h2> </h2>
<h2> </h2>
<h2> </h2>
</div>
<div class="col-md-4 col-md-offset-4 ">
<form id='loginform' action='/users/login/' method='post' accept-charset='UTF-8'>
{% csrf_token %}
<fieldset >
<div class="form-group">
<input type="text" name="mobile_number" id="mobile_number" tabindex="1" class="form-control" placeholder="Mobile Number" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Enter Password">
</div>
</fieldset>
<button type="submit" class="btn btn-primary btn-xl btn-block">LOG IN</button><br><br>
<span class="login-error"></span>
<h1> </h1><h1> </h1>
</form>
</div>
</div>
In addition to event.preventDefault();, it might be a good idea to also call event.stopPropagation() in this case.
Use : 'event.preventDefault()' or 'return false' after the ajax call.

After Angularjs validation is true do a normal form submit

I am implementing AngularJS on an existing web application that requires a common HTTP POST like you would do without AngularJS.
Does any one have a work around to do that?
i have tried setting action="#" and action="." and just action and then do some jquery to inject a action like this. but nothing works
<script type="text/javascript">
$("form").get(0).setAttribute( "action", "test.html" );
</script>
HERE IS MY FORM AND CODE
//MY FORM
<form name="userForm" ng-submit="submitForm(userForm.$valid)" xt-form novalidate>
<div class="form-group">
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn.$invalid && !userForm.fornavn.$pristine }">
<label class="control-label" for="textinput">Fornavn <span class="star-color">*</span></label>
<input autocomplete="off" type="text" value="<?php echo set_value('fornavn'); ?>" name="fornavn" ng-model="userFormData.fornavn" class="form-control" xt-validate msg-required="Du skal udfylde dit Fornavn" required>
</div>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.efternavn.$invalid && !userForm.efternavn.$pristine }">
<label class=" control-label" for="textinput">Efternavn <span class="star-color">*</span></label>
<input autocomplete="off" type="text" value="<?php echo set_value('efternavn'); ?>" name="efternavn" ng-model="userFormData.efternavn" class="form-control" xt-validate msg-required="Du skal udfylde dit Efternavn" required>
</div>
</div>
<button id="membership-box__payBtn" type="submit" ng-model="userFormData.betaling" name="betaling" class="btn btn-success text-uppercase">Gå til betaling</button>
</form>
//CODEIGNITER CONTROLLER
if (isset($_POST['betaling'])) {
$data['tilBetaling'] = array(
'oprettelse' => $this->input->post('oprettelse'),
// 'medlemskab' => $this->input->post('medlemskab'),
'tilBetaling' => str_replace(',', '.', $this->input->post('tilBetaling')),
'pr_maaned' => $this->input->post('pr_maaned'),
'start_date' => $this->input->post('start_date'),
'til_dato' => $this->input->post('til_dato'),
'pakke' => $this->input->post('pakke'),
'type' => $this->input->post('medlemskabTypeFinal'),
'getCenter' => $this->input->post('getCenter'),
'medlemskabPakkePID'=> $this->input->post('medlemskabPakkePID'),
'ekstraInput' => $this->input->post('ekstraInput'),
'periode_price' => $this->input->post('periode_price'),
'kampagneTag' => $this->input->post('kampagneTag'),
// 'header' => $this->input->post('header'),
);
//Gem array til session
$_SESSION['betaling'] = $data['tilBetaling'];
}
If you want to do a normal submit, you can handle ngClick in your controller:
HTML
<div ng-controller="ctrl">
<form name="userForm" action="user/add" method="post">
Name: <input name="name" ng-model="user.name" />
...
<button ng-click="onSubmit(userForm)">Submit</button>
</form>
</div>
JS
app.controller('ctrl', function($scope) {
$scope.onSubmit = function(form) {
if (form.$valid) {
var e = document.getElementsByName(form.$name);
e[0].submit();
}
}
});
An Alternative Solution
As an alternative, consider leveraging services, and redirecting after a successful POST in AngularJS.
HTML
<div ng-controller="ctrl">
<form name="userForm" ng-submit="onSubmit(user)">
Name: <input name="name" ng-model="user.name" />
...
<button type="submit">Submit</button>
</form>
</div>
JS
app.factory('UserService', function($http) {
return {
addUser: function(user) {
return $http({method:'POST', url:'api/user/add', data: user });
}
}
});
app.controller('ctrl', function($scope, $location, UserService) {
$scope.onSubmit = function(user) {
if ($scope.userForm.$valid) {
UserService.addUser(user).success(function() {
$location.path('/user/addSuccessful')
});
}
}
});
Even if you do an AngularJs submit, the request does not go to server. The control still remains on client side. Then you can post the data/form etc through $http service. You can inject $http service in your controller. as
app.controller('reviewCtrl', ['$http', function($http){
$scope.addReview = function(product){
//use $http service here
// Simple POST request example (passing data) :
$http.post(' / someUrl ', {msg:' hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}]);
note: please review the syntax before running the code.
To submit the Angular Js form ONLY after Angular validations are through or passed, you must use reviewForm.$valid flag chack in ng-submit.
With this flag check, the form will not get submitted until all validations are passed.
<form name="reviewForm" ng-controller="reviewCtrl" ng-submit="reviewForm.$valid && reviewCtrl.addReview(product)" novalidate>
....
....
</form>

Categories

Resources