AngularJS $http post request being cancelled - angularjs

I'm trying to send a post form to a PHP script, and every time, the POST request shows as canceled.
My controller looks like this:
var authenticationControllers = angular.module('authenticationControllers', []);
authenticationControllers.controller('Authentication', ['$scope', '$http', function($scope, $http) {
$scope.WPlogin = function () {
var mydata ={
'action': 'ajaxlogin',
'username': $scope.user.username,
'password': $scope.user.password,
'security-login': pluginParams.nonce,
'_wp_http_referer': '/s/play/'
};
$http({
method: 'POST',
url: $scope.ajaxURL, //This is defined earlier, I'm sure this is valid
data: jQuery.param(mydata),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
console.log(data.message);
}).error(function(e){alert('error')});
};
}]);
And the form looks like this:
<div class="white-popup mfp-hide" id="login-modal" ng-controller="Authentication">
<form name="loginform" id="loginform" novalidate>
<h1>Login</h1>
<p class="status"></p>
<label for="username">Username</label>
<input id="username" type="text" name="username" ng-model="user.username" ng-required="true">
<label for="password">Password</label>
<input id="password" type="password" name="password" ng-model="user.password" ng-required="true">
<a class="lost" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a>
<button class="submit_button" ng-disabled="loginform.$invalid" ng-click="WPlogin()" type="submit" name="submit"> Login</button>
</form>
</div>
Whenever I try to submit the form, the error alert pops up, but no console errors. Then, the page reloads, and I can see the form parameters in the URL (like a get request), and if I then submit my form (without deleting the get parameters), then the request is a success.
Can anyone tell me what I'm doing wrong?
Update
I added $event.preventDefault(); to the form (passing $event from the form), and now it all works as expected, but I don't understand, why do I need that? I thought AngularJS would automatically prevent the form submission.

Related

AngularJS submit form to db via php

i'm approching angularJS and i'd like to submit a form to db via php.
i tried this but it does not work.
any help?
i get an error when i click the submit button.
thanks.
//index.html
angular.module("myApp")
.controller("addUtentiCtrl", function($scope, $http) {
$scope.utenteForm = {};
$scope.submit = function() {
$http({
method : 'POST',
url : 'backInsertUtenti',
data : param($scope.utenteForm),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function() {
alert("Dati inseriti correttamente!");
})
.error(function() {
alert("Errore inserimento dati!");
});
};
});
//aggiungiUtente.html
<form ng-submit="submit()" ng-controller="addUtentiCtrl" novalidate>
<input type="text" ng-model="utenteForm.nome" name="nome" ng-maxlength="10" ng-required="true">
<input type="text" ng-model="utenteForm.cognome" name="cognome" ng-maxlength="10" ng-required="true">
<input type="text" ng-model="utenteForm.citta" name="citta" ng-maxlength="10" ng-required="true">
<input ng-enable="utenteForm.$valid" type="submit" id="submit" value="Submit" />
</form>
//backInsertUtenti.php
<?php
//define of variable for the connection
$db= new mysqli($host,$username,$password,$db_name);
$sql=$db->prepare("INSERT INTO utenti (id, nome, cognome, citta) VALUES (0, ?, ?, ?)");
$sql->bind_param('sss',$_POST['nome'],$_POST['cognome'],$_POST['citta']);
$sql->execute();
?>

AngularJS error: TypeError: v2.login is not a function

I would like to call the login function when I click the login button but keep getting the error message in the title. Can someone point out the error in my script?
login.js code below:
/*global Firebase, angular, console*/
'use strict';
// Create a new app with the AngularFire module
var app = angular.module("runsheetApp");
app.controller("AuthCtrl", function ($scope, $firebaseAuth) {
var ref = new Firebase("https://xxxxx.firebaseio.com");
function login() {
ref.authWithPassword({
email : "xxxxx",
password : "xxxx"
}, function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
And the code for login.html is also below:
<div class="container" style="max-width: 300px">
<form class="form-signin">
<h2 class="form-signin-heading" style="text-align: center">Please Sign In</h2>
<input type="text" class="form-control" name="username" ng-model = "username" placeholder="Email Address" required="" autofocus="" />
</br>
<input type="password" class="form-control" name="password" ng-model = "password" placeholder="Password" required=""/>
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login()">Login</button>
</form>
</div>
Edge case here, but I want to mention it for posterities' sake. I got this same error when using the controllerAs pattern with a form name with the same value as ng-submit. For example:
<form name="authCtrl.signUp" ng-submit="authCtrl.signUp()">
Throws: TypeError: v2.signUp is not a function
The solution was to change the name of the form to something different:
<form name="authCtrl.signUpForm" ng-submit="authCtrl.signUp()">
In my case, I was having an exact same issue as yours. However, coming across gkalpak's answer to such a scenario helped me out.
Turned out to be what I was calling was addBuddy() function, from a form named "addBuddy". The solution was to change the name of either of the two things to make one stand out or differentiable from the other. I changed the name of the form to "addBuddyForm" and voila! My function worked!
Here's a snippet of my case:
<form name="addBuddy" class="form-horizontal" novalidate>
...
<button class="btn btn-sm btn-info" ng-click="addBuddy()>Submit</button>
Which, I changed to:
<form name="addBuddyForm" class="form-horizontal" novalidate>
...
<button class="btn btn-sm btn-info" ng-click="addBuddy()>Submit</button>
...and it worked! :)
In AngularJS call the function from view it must be in the $scope.
JS
// exposes login function in scope
$scope.login = login;
HTML
<div class="container" ng-controller="AuthCtrl" style="max-width: 300px"> <!-- I notice here for include ng-controller to your main div -->
<form class="form-signin">
<h2 class="form-signin-heading" style="text-align: center">Please Sign In</h2>
<input type="text" class="form-control" name="username" ng-model = "username" placeholder="Email Address" required="" autofocus="" />
</br>
<input type="password" class="form-control" name="password" ng-model = "password" placeholder="Password" required=""/>
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login()">Login</button>
</form>
This may not be specific to your problem, but I was also getting this error and it took a bit to figure out why.
I had named both a function and a variable the same, with the variable assigned in the function, and so the assignment of the variable was overriding the function and it was exploding on a second run.
You'll notice in the example the uploadFile() function as an upload.uploadFile = true; This was a wonderful file that was meant to be upload.uploadingFile - a flag used to control the behavior of a spinner. Once that was fixed, the issue went away.
Example:
(function()
{
'use strict';
angular.module('aumApp.file-upload')
.controller('FileUploadCtrl', FileUploadCtrl);
function FileUploadCtrl($scope, $http)
{
upload.uploadFile = function()
{
upload.uploadFile = true;
var backendUrl = '/ua_aumcore/events/api/v1/events/uploadFile';
var fd = new FormData();
fd.append('file', upload.src);
$http({ url: backendUrl, data: fd, method: 'POST', transformRequest : angular.identity, headers: { 'Content-Type' : undefined } })
.then(function uploadSuccess(response)
{
upload.data = response.data;
upload.message = "Uploaded Succesfully.";
upload.uploadSuccess = true;
upload.uploadingFile = false;
},
function uploadFailure(response)
{
upload.message = "Upload Failed.";
upload.uploadSuccess = false;
upload.uploadingFile = false;
});
};
}
FileUploadCtrl.$inject = ['$scope', '$http'];
})();
To be callable from the view, a function must be in the $scope. Add
$scope.login = login;
to the JS code of the controller.
You also need to actually use that controller. Change
<div class="container" style="max-width: 300px">
to
<div ng-controller="AuthCtrl" class="container" style="max-width: 300px">
This is all fundamental stuff. My advice would be to learn from an AngularJS tutorial before going further.
Two enable two-way binding you have to assign your login function to $scope. Replace your code for function with this:
$scope.login=function() {
ref.authWithPassword({
email : "nick.koulias#gmail.com",
password : "Jaeger01"
}, function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
}
It may be a late answer by me.
But It working for me
Check form name you set
e.g. ng-form="login"
and function name
e.g. ng-click="login()"
Then it will not work . You have to change one of them.
e.g. ng-form="loginForm"
Explanation:
AngularJS 1.x registers any form DOM element that has a name property in $scope via formDirectiveFactory. This directive automatically instantiates form.FormController if the above is true:
If the name attribute is specified, the form controller is published onto the current scope under
from: angular.js:24855
Hence if you have a <form name=myForm> it will override your $scope.myForm = function() { ... }

angular form validation not working on form submitting

I'm new in angularJS. My form doesn't validate on submit. I use angular-validation module downloaded from bower. How can I validate form on submit button?
I use refrence from https://github.com/huei90/angular-validation/blob/master/API.md
My form is like that:
<div ng-controller="nameController">
<form name="myForm" ng-submit="submitForm()">
<label for="ud_fname"></label>
<input
type="text"
id="ud_fname"
name="ud_fname"
placeholder="First Name"
ng-model="form.ud_fname"
valid-method="blur"
validator="required"
required-error-message="Required"
>
<label for="ud_lname"></label>
<input
type="text"
id="ud_lname"
name="ud_lname"
placeholder="Last Name"
ng-model="form.ud_lname"
valid-method="blur"
validator="required"
required-error-message="Required"
>
<input type="submit" value="Add" class="pure-button" />
<input type="reset" value="Reset" class="pure-button" />
</form>
My Controler is like that:
app.controller('nameController', function ($scope, $http) {
// insert record
$scope.submitForm = function (){
var url= 'functions/insert.php';
var data = {
ud_fname: $scope.form.ud_fname,
ud_lname : $scope.form.ud_lname,
};
console.log(data);
$http({
url: url,
data: data,
method: 'post'
}).success(function (response){
console.log(response);
});
};
});
You need to validate on ng-submit & don't call an submitForm if its not valid form
ng-submit="myForm.$valid && submitForm()"
You need to validate the form in your controller as well. Also, it would be better if you pass the form (user) as a parameter. If you are writing unit tests (which you should), it would be easier to test your method easily in that case as there will be no coupling with $scope.
P.S. Migrate your code to controllerAs syntax, you won't regret it.
$scope.submitForm = function (user, isValid){
if (isValid) {
var url= 'functions/insert.php';
var data = {
ud_fname: user.ud_fname,
ud_lname : user.ud_lname,
};
console.log(data);
$http({
url: url,
data: data,
method: 'post'
}).success(function (response){
console.log(response);
});
}
};
And your form will become:-
<form name="myForm" ng-submit="submitForm(form, myForm.$valid)">
.....
</form>

AngularJS $http.post request is canceled by Chrome

I've been googling this for hours...
here's my angularJS code:
var FrontControllers = angular.module('FrontControllers', [] );
FrontControllers.controller('LoginController', ['$scope', '$http', function($scope, $http){
$scope.user = {};
$scope.login = function() {
console.log($scope.user);
$http({
url: '/webapi/login',
method: 'POST',
data: $scope.user
}).success(function (data) {
alert("success!");
}).error(function(data) {
alert("failed =(");
});
};
}]);
here's the accompanying html
<div ng-controller="LoginController" id="login" class="box">
<form novalidate role="form" action="/webapi/login" id="loginForm">
<label for="signin" class="sr-only">Email or Username</label>
<input ng-model="user.username" type="text" autofocus class="form-control input-lg" id="username" name="username" size="20" placeholder="email or username">
<label for="password" class="sr-only">Password</label>
<input ng-model="user.password" type="password" class="form-control input-lg" id="password" name="password" size="10" placeholder="password">
<button ng-click="login()" type="submit" class="btn btn-lg btn-bright btn-block">Login</button>
</form>
</div>
No matter what I do, I end up with a POST request that gets cancelled. I've previously succeeded in logging in to /webapi/login with standard jQuery ajax code. The server is configured for AJAX, so there's no need for a urlencode header. The Payload looks correct, identical to the one that sent by jQuery ajax.
What might be the problem?
This is from Chrome developer/network:
Provisional headers are shown
Accept:application/json, text/plain, */*
Content-Type:application/json;charset=UTF-8
Origin:http://ec2-54-86-242-50.compute-1.amazonaws.com
Referer:http://ec2-54-86-242-50.compute-1.amazonaws.com/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id:BB96CDC3-AD63-D024-E814-4726DF4843D8
Angular will not preventDefault() if the action parameter is set. See here
For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.
You should probably also use ng-submit="login() on the <form> instead of ng-click, so that it will submit the form when the user presses Enter
Try removing form's
action="/webapi/login"
and button's
type="submit"

Submit form with ng-submit and trigger synchronous post request

I have a form that I want to trigger validation on when the user clicks submit. If the validation fails, then suitable error messages are displayed. This much works.
However if the validation passes I want the form to submit a synchronous POST request with full page reload as if the action and method parameters were set as usual.
How does one achieve trigger the normal post action (not AJAX) from the ng-submit function on the AngularJS scope?
My form of course looks basically like the following:
<form id="myForm" name="myForm" ng-submit="formAction(this, models)">
...
<input type="submit" value="Submit">
</form>
The best I can think of is to mirror the contents of the form with another hidden form submitting that one, but there must be a better way!
TO CLARIFY: If validation passes, I need the form submission to essentially behave like a normal synchronous post form submission which lands the user at the page returned by the server from the post request.
http://plnkr.co/edit/cgWaiQH8pjAT2IRObNJy?p=preview
Please check this plunkr
Basically what I am doing is passing the $event object. form is the target of the event object, and we can submit it.
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function($event) {
if ($scope.text) {
$scope.list.push(this.text);
if(this.text === 'valid'){
$event.target.submit();
}
$scope.text = '';
}
};
}
Try inside formAction after you've submitted the data:
$route.reload();
I dont think you need to do a full page refresh. You have a single page app I am assuming; use it. Try something like this:
<section class="contact">
<article>
<h1>Contact</h1>
<form role="form" name="contactForm" ng-submit="formSubmit(contactForm)">
<div class="form-group">
<input class="form-control" ng-model="name" name="name" id="name" type="text" placeholder="Name" required/>
</div>
<div class="form-group">
<input class="form-control" ng-model="email" name="email" id="email" type="email" placeholder="Email Address" required/>
</div>
<div class="form-group">
<textarea class="form-control" ng-model="message" name="message" id="message" rows="5"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Send Message</button>
<a class="btn btn-default btn-lg" href='mailto:me#something.net'>Or email me</a>
</div>
</form>
</article>
'use strict';
MyApp.controller('ContactController', function ContactController ($scope, EmailService) {
$scope.formSubmit = function(form) {
EmailService.send(form).then(function(data) {
if(data.message.sent) {
$scope.resetForm();
alert("Message Sent");
}
else {
alert("Something went wrong. Try emailing me.");
}
});
}
$scope.resetForm = function() {
$scope.name = "";
$scope.email = "";
$scope.message = "";
}
});
MyApp.factory('AjaxService', function AjaxService ($q, $http) {
return {
http: function(ajaxParams) {
var deferred = $q.defer();
$http(ajaxParams)
.success(function (data, status, headers, config) {
deferred.resolve({
success: true,
status: status,
message: data
});
})
.error(function (data, status, headers, config) {
deferred.reject({
success: false,
status: status,
message: "Http Error"
});
});
return deferred.promise;
}
}
});
MyApp.factory('EmailService', function EmailService (AjaxService) {
return {
send: function(emailData) {
var ajaxParams = {
method: 'POST',
url: ''//where ever your form handler is,
data: {
name: emailData.name.$modelValue,
email: emailData.email.$modelValue,
message: emailData.message.$modelValue
},
cache: false
}
return AjaxService.http(ajaxParams);
}
}
});

Resources