POST request problems during JSON response using AngularJS - javascript

I am having an issue while using JSON server for login form. I have login credentials like Username and password and trying to execute it. I have used POST on the server, specifying username and password inserted by the user. The server should execute a query on the specified condition, to check if there are any rows with that name and password. If yes return true, if false return false. then the client should parse this response.
This is my HTML code :
<form ng-submit="loginform(logcred)" name="logform"><br/><br>
<tr ng-repeat="logcred in loginfo"></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>
<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:
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
$http.get('http://localhost:3000/loginfo')
.then(
function successCallback(response){
$scope.loginfo == response.data;
$scope.loginform = function(loginfo,username,password){
console.log(loginfo);
$http({
url :'http://localhost:3000/loginfo',
method : 'POST',
data : loginfo
})
.then(
function successCallback(response){
$scope.loginfo = response.data;
if (username === username && password === password) {
console.log(response);
}
else
{
console.log("Error: " + response)
}
});
}
});
I am getting the response properly from my server. But when I match the data using POST request using if condition, there I am not understanding what mistake I am doing ?
Any help / advice would be greatly appreciated.

i didnt understand if your problem is server side or client ? is your problem at
if (username === username && password === password) {
console.log(response);
}
you may use == insted of ====

You are comparing the data with itself.
username === username && password === password
Should be
username === $scope.loginfo.username && password === $scope.loginfo.password
Still, any kind of security validation should be done on the server rather than on the client.
Also, you seem to be new to Angular. Let me recommend to you the John Papa's Styleguide.

Related

How can I control the flow of using JavaScript first and then send the control to the back end server created using flask framework?

I am using Flask Framework..
I have a form tag in the front end for login id and password and a submit button.
I want to use JavaScript in the front end to verify the data provided by the user in the form field and then if everything is okay, then I want to send the data provided by the user to the back end server and process it using python..
But how can I control the process that when the user click on the submit button the control will go to the JavaScript code and then after validation, the data is sent to the back end server
In the snippet I have given a dummy example. In that my doubt is how to first send the control to the validate_login_form() written in Java Script and then after validation the control should go to the {{url_for('home')}} written in the action part using the Jinja2 template engine
Here the trouble that i am having is, after filling up the form, when the user clicked of the submit button, the control goes fine to the Java Script function written to validate the form but even if the Java Script returns false, the control automatically goes to the back end server.
But what i want to do is if the Java Script returns false, the control should stop there and ask the user to again fill in the form.
function validate_login_form(){
let login_id = document.getElementById('login_id').value
let password = document.getElementById('password').value
if(login_id == '' && password == ''){
alert('please enter the login id and password')
return(false)
}
else if(login_id == '' && password != ''){
alert('please enter the login id')
return(false)
}
else if(login_id != '' && password == ''){
alert('please enter the password')
return(false)
}
else{
if(login_id == 'test' && password == 'test'){
return(true);
}
else{
alert('please enter the valid login id and password')
return(false)
}
}
}
<html>
<head>
</head>
<body>
<form action="{{url_for('home')}}" onsubmit="validate_login_form()">
<label for="login_id">LogIn</label>
<input type="text" name="login_id" placeholder="login Id" id="login_id">
<label for="password">Password</label>
<input type="password" name="password" placeholder="password" id="password">
<br><br>
<input type="submit" value="submit" >
</form>
<script src="{{ url_for('static', filename='scripts/login.js') }}"></script>
</body>
</html>
Simple: https://www.w3schools.com/jsref/event_onsubmit.asp.
There your go:
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input type="submit">
</form>
<script>
function myFunction() {
return true;
}
</script>
HTML from example:
<form method="POST" id="myForm">
<input type="email" name="email" id="email"/>
<input type="password" name="password" id="password"/>
<button type="submit">Login</button>
</form>
javascript:
var myForm = document.getElementById("myForm");
myForm.onsubmit = function(e){
e.preventDefault();
// validate here and produce data
fetch('/mypage', {
method: "POST",
credentials: "include",
cache: "no-cache",
body: data,
headers: new Headers({
"Content-Type": "application/json",
}),
})
.then((response) => {
if (response.status !== 200) {
// handling if status is not ok(200)
}
response.text().then((res) => {
// response handling
if(res === "success"){
// redirect to homepage or do anything
} else {
// something went wrong
}
});
})
.catch((err) => {
// error handle
});
}
Flask/Python:
from flask import request
#app.route('/mypage', methods=['GET', 'POST'])
def myPage():
if request.method == "POST" and request.json:
data = request.json
# send data to database
return 'success', 200
The only problem here in the codes are in the form tag in html,
I should have written onsubmit=return validate_login_form()
instead of onsubmit=validate_login_form()
By this code if the JavaScript function returns true then the page will be redirected to the url written in the action field of the form tag
and if the JavaScript function returns flase then the control will remain in the same page without being redirected.
That's how the flow can be controlled
function validate_login_form(){
let login_id = document.getElementById('login_id').value
let password = document.getElementById('password').value
if(login_id == '' && password == ''){
alert('please enter the login id and password')
return(false)
}
else if(login_id == '' && password != ''){
alert('please enter the login id')
return(false)
}
else if(login_id != '' && password == ''){
alert('please enter the password')
return(false)
}
else{
if(login_id == 'test' && password == 'test'){
return(true);
}
else{
alert('please enter the valid login id and password')
return(false)
}
}
}
<html>
<head>
</head>
<body>
<form action="{{url_for('home')}}" onsubmit="return validate_login_form()">
<label for="login_id">LogIn</label>
<input type="text" name="login_id" placeholder="login Id" id="login_id">
<label for="password">Password</label>
<input type="password" name="password" placeholder="password" id="password">
<br><br>
<input type="submit" value="submit" >
</form>
<script src="{{ url_for('static', filename='scripts/login.js') }}"></script>
</body>
</html>

Using <Form>, jQuery, Sequelize and SQL to Login and route

My goal is to use the values of the IDs #username-l and #pwd-l in a html form when the user clicks the button submit, have it compare those values to values in a SQL database and if the values equal exactly the values in the database then route the user to a specified route (for now just /user is fine for testing). Currently it routes to /? with no errors which is not specified anywhere. The console shows the query is returning username = null and password = null. I have seeds in the DB called username = test password = test for testing. Any help is appreciated!
HTML:
<form id="login-form">
<div class="form-group">
<label for="username-l">Username:</label>
<input type="username" class="form-control" id="username-l" placeholder="Enter username">
</div>
<div class="form-group">
<label for="pwd-l">Password:</label>
<input type="password" class="form-control" id="pwd-l" placeholder="Enter password">
</div>
<button id="login-button" type="submit" class="btn btn-default">Login</button>
</form>
SEQUELIZE:
app.get("/api/users", function(req, res) {
db.User.findAll({
where:
{
username: req.body.username,
password: req.body.password
}
}).then(function(dbUser) {
// res.json(dbUser);
if (req.body.username === dbUser.username && req.body.password === dbUser.password) {
res.redirect("/users");
} else {
console.log("error");
}
});
});
LOGIN.JS:
$("#login-button").on('click', function() {
var username = $("#username-l").val().trim();
var password = $("#pwd-l").val().trim();
$.get("/api/users", function(data){
console.log(data);
if (username === data.username && username === data.password) {
reRoute();
} else {
console.log("that does not exist");
}
});
});
function getUser(userData) {
$.get("/api/users", userData).then(reRoute());
}
function reRoute() {
window.location.href = "/users";
}
First of all, you're doing a GET request, which, as much as I know HTTP, dosn't have body.
Second, I'm no expert in jQuery, nor I've ever used it, but a quick Google search showed that second parameter is passed as a query string, which is how GET is supposed to work. If you have any data to send, you send it via query string, not through request body.
Therefor, the problem you have is with the server side code, where you read username and password from body instead from query string. So in order for this to work, you need to extract username and password from query like this (I'm guessing you're using Express):
app.get("/api/users", function(req, res) {
const username = req.query.username;
const password = req.query.password;
// do the rest of the stuff with Sequelize and bussiness logic here
});
On the sidenote, you're full router callback has some bad things, like redundant checking if username and password match from the one retrieved from DB. You've already asked Sequelize to retrieve a row from the DB where username and password are the ones you recived from the frontend, and because of that, you don't need to check if instance's username and password matches the one you have. The thing you do need to check if the instance is null, because that means that there is no user with that username and password in your DB. So the "fixed" code should look something like this:
app.get("/api/users", function(req, res) {
const username = req.query.username;
const password = req.query.password;
db.User.findAll({
where: {
username,
password
}
}).then(function(dbUser) {
// res.json(dbUser);
if (dbUser != null) {
res.redirect("/users");
} else {
// you'd maybe like to set response status to 404
// also some user friendly error message could be good as response body
console.log("Error: user not found");
}
});
});
I hope you get the idea of the flow and where was your mistake.

Obtaining output of php file with Javascript

I have a php file stored remotely. It uses post to take 2 variables, "username" and "password", which will then echo either Valid or Invalid depending on it's existence in my database. I currently use this with my android application to log users in.
I would like to use this same script for logging into my website that I am building. I need to be able to pass 2 variables that I have obtained from an HTML form to a javascript function which will take the variables, run them though the php query, read the echoed output and decide to return true or false to the form. Below is the code I currently have for the script
Javascript code:
<script type="text/javascript">
function Login(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert ("Please fill in username and password fields");
return false;
}
$.post("my_query_url.php",{username:username, password:password}, function(data) {
if (data.toLowerCase == "valid")
return true;
else
return false;
});
}
</script>
HTML form:
<form action="Main.html" method="post" onsubmit=" return Login();">
Username: <br>
<input type="text" name="username" id="username"><br>
Password: <br>
<input type="password" name="password" id="password"><br><br>
<input type="submit" value="Login">
</form>
Currently, it always sends the user to my Main.html page with any non-empty username/password input.
I'm not very well versed in these two languages, but I need to learn quickly as they are important for my Senior Project class semester, and especially these next two weeks. Is this possible to do with Javascript and HTML only? Some pointers will be much appreciated! Thank you!
You actually are almost all the way there. You just need to return false from your Login function to prevent the default action of the form from triggering (which is to redirect to main.html). Then, instead of relying on the form to redirect the user, you will need to do so yourself via javascript.
<script type="text/javascript">
function Login(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert ("Please fill in username and password fields");
return false;
}
$.post("my_query_url.php",{username:username, password:password}, function(data) {
if (data.toLowerCase() === "valid")
window.location.href = "./Main.html"; //redirect the user
else
return false;
});
return false
}
</script>

Why is my newsletter form not working on Amazon CloudFront?

I am using HTML and using amazon EC2 (Linux free tier). I would like to use CloudFront, but my newsletter won't work. I am not an AWS expert, and I don't have a clue as to why it won't work on CloudFront.
My newsletter form looks like this:
<form id="subscribe" class="form" action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group form-inline">
<input size="15" type="text" class="form-control required" id="NewsletterName" name="NewsletterName" placeholder="Your name" />
<input size="25" type="email" class="form-control required" id="NewsletterEmail" name="NewsletterEmail" placeholder="your#email.com" />
<input type="submit" class="btn btn-default" value="SUBSCRIBE" />
<span id="response">
<? require_once('assets/mailchimp/inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</span>
</div>
</form>
and my js file looks like this:
jQuery(document).ready(function() {
jQuery('#subscribe').submit(function() {
// update user interface
jQuery('#response').html('<span class="notice_message">Adding email address...</span>');
var name = jQuery('#NewsletterName').val().split(' ');
var fname = name[0];
var lname = name[1];
if ( fname == '' ) { fname=""; }
if ( lname == '' || lname === undefined) { lname=""; }
// Prepare query string and send AJAX request
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()),
success: function(msg) {
if (msg.indexOf("Success") !=-1) {
jQuery('#response').html('<span class="success_message">Success! You are now
subscribed to our newsletter!</span>');
} else {
jQuery('#response').html('<span class="error_message">' + msg + '</span>');
}
}
});
return false;
});
});
and my php file looks like this:
<?php
function storeAddress(){
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('mymailchimpapi');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "myuniqueid";
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a
confirmation link.';
}else{
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
The form works when I access it without using CloudFront, but I am worried of the server bandwidth that's why I want to use CloudFront. What happens is that when you click the submit button, the "adding email address" message will just appear for 1 second, and the email address entered is ignored.
Please make sure your CloudFront distribution is actually configured to handle POST/PUT requests. Take a look here for details: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesAllowedHTTPMethods

Ajax Post between angularjs and symfony2 (Notice: Undefined index)

I'm very new to symfony2 php framework but I know that its MVC for backend. I'm trying to create a form which get stored in the database and then an email is sent to the user with the same info that he/she typed in the form. To do that, I used doctrine, swiftmailer and entity in the symfony2 framework.
When I use < form method='post' action='saveIndex' >< /form >, it works just fine but when I'm trying to implement angularjs's AJAX to post my data, I'm getting Notice: Undefined index error.
Html (in twig template):
<form class="productForm">
<div class="inputs" style="float: left">
<input type="text" name="productId" data-ng-model="signup.user.productId"/>
<input type="text" name="firstName" data-ng-model="signup.user.firstName"/>
<input type="text" name="lastName" data-ng-model="signup.user.lastName"/>
<input type="email" name="email" data-ng-model="signup.user.email"/>
<input type="text" name="price" data-ng-model="signup.user.price"/>
<input type="text" name="timeStamp" data-ng-model="signup.user.time"/>
<textarea name="comments" data-ng-model="signup.user.comments"></textarea>
<button type="submit" name="submit" class="btn btn-primary" ng- click="submit(signup.user)">Submit Request</button>
</div>
</div>
</form>
app.js:
myApp.controller('mainController',[
'$scope',
'$location',
'$http',
'$window',
'$rootScope',
function($scope, $location, $http, $window, $rootScope){
$scope.submit = function (user) {
$http({
method: 'POST',
url: 'saveIndex',
data: $scope.signup
})
.success(function(data, status){
$log.warn(data, status); //remove for production
$location.path('success');
})
.error(function(data, status){
$log.warn(data, status); //remove for production
});
}
}
]);
symfony2 controller:
// Save Information
public function saveIndexAction(){
$post = new Post(); // Call to entity named Post
$request = $this->get('request');
$params = $request->request->all();
$session = $this->get('session');
$this->saveIndex(
$params['productId'], <- GETTING UNDEFINED INDEX ERROR
$params['firstName'],
$params['lastName'],
$params['email'],
$params['price'],
$params['timeStamp'],
$params['comments'],
$session
);
$post->setProductId($params['productId']);
$post->setFirstName($params['firstName']);
$post->setLastName($params['lastName']);
$post->setEmail($params['email']);
$post->setPrice($params['price']);
$post->setTimeStamp($params['timeStamp']);
$post->setComments($params['comments']);
// Store information in the database
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
// Send the email
$this->mailAction
(
$post->getId(),
$params['productId'],
$params['firstName'],
$params['lastName'],
$params['email'],
$params['price'],
$params['timeStamp'],
$params['comments']
);
// Return the response
//return new Response('Info Submitted'.$post->getId());
$return=json_encode($post);//json encode the array
return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
}
I don't know how to make AJAX POST with with symfony 2 controller and get the response back to Angularjs to perform client side routing. Please any help is appreciated. Thank you.
So, upon var_dump($params), I found the output to be array (size = 0) undefined.
So, I included the following code:
protected function getRequestJson(){
$params = null;
$content = $this->get("request")->getContent();
if (!empty($content))
{
$params = json_decode($content, true);
}
return $params;
}
public function saveIndexAction(){
$post = new Post();
$signup_params = $this->getRequestJson();
//flatten signup parameters
$params = array();
foreach ($signup_params as $p) {
if (is_array($p)) {
foreach($p as $key=>$val) {
$params[$key]=$val;
}
}
}
}
And it worked.

Categories

Resources