I am quite new to all web development, and I am struggling to find what I am looking for. I am using springboot.
My expectation:
The user will open a page, fill the form details, click on Submit button and get redirected to a new page. The form information will be stored on a hashmap and used on my backend.
Reality:
The user opens the page, fill the form details, click on the Submit button but don't get redirected to a new page. Nonetheless, the information is stored on a hashmap.
HTML:
<div class="container" ng-app="app">
<h1>Configurador de Plugin</h1>
<div ng-controller = "plugins">
<form>
<div class="form-group">
<label>Database Details:</label>
<input type="text" class="form-control" id="hostname" placeholder="Informe o Endereço do Servidor" ng-model="hostname">
<input type="text" class="form-control" id="port" placeholder="Informe a porta" ng-model="port">
<input type="text" class="form-control" id="username" placeholder="Informe o usuário" ng-model="userdb">
<input type="text" class="form-control" id="userpass" placeholder="Informe a senha" ng-model="userpass">
<input type="text" class="form-control" id="database" placeholder="Informe qual o banco de dados" ng-model="database">
<button ng-click="validar()" type="submit" class="btn btn-default">Search</button>
<div ng-show="visivel">
<p>{{valor}}</p>
</div>
</form>
<div>Make a choice</h3>
</div>
<div class="radio">
<label><input ng-model="plugin.Name" value="test" type="radio" name="Test">Test</label></div>
<div class="radio">
<label><input ng-model="plugin.Name" value="v2" type="radio" name="V2">V2</label></div>
<div class="radio">
<label><input ng-model="plugin.Name" value="v1" type="radio" name="V1" >V1</label></div>
Texto:
<p>{{plugin.Name}}</p>
<br>
<button ng-click="sendForm()" type="submit" class="btn btn-default">Search</button>
</div>
</div>
The JS:
app.controller('plugins', function($scope, $http, $location) {
$scope.validar = function(){
$scope.visivel = true;
$scope.valor = $scope.hostname,
console.log($scope.hostname)
}
$scope.enviarForm = function(){
var url = $location.url() + "test";
var config =
{
headers :
{
'Content-Type': 'application/json;charset=utf-8;'
}
}
console.log($scope.hostname);
var data =
{
hostname: $scope.hostname,
port: $scope.port,
username: $scope.username,
userpass: $scope.userpass,
database: $scope.database
};
$http.post(url, data, config).then(function (response)
{
$scope.postResultMessage = "Sucess!";
},
function (response) {
$scope.postResultMessage = "Fail!";
});
}
});
The Controller:
#RequestMapping("/test")
public ModelAndView CadastroEnotas(#RequestBody HashMap<String, Object> data) {
ModelAndView modelAndView = new ModelAndView("newPage");
modelAndView.addAllObjects(data);
return modelAndView;
}
So, my expectation, is that the above Controller would send the user to newPage, but it doesn't.
I am googling but I am likely misunderstanding the concept of ModelAndView or maybe how to execute the function on my js...
I think the closest to what I am looking for is described here: angular event success when submit form it opens popup, but I failed to make it work. Could someone point me what I am doing wrong?
Propably use redirect.
ModelAndView modelAndView = new ModelAndView("redirect:/newPage.htm");
modelAndView.addAllObjects(data);
return modelAndView;
Or try redirect after post request: $location.path('/newPage').
Check something like this: Redirects
Related
I am trying to save a ViewModel object from a partial view in a modal, and I get a 404 error when I try to post it. The url is being called, but the ViewModel data isn't being sent. I have been reading similar questions on here and on MSN for hours and nothing I've tried fixes the problem. I took out the repetitive days of the week code for brevity, but I can
add them back in if anyone wants a complete working example. Here is the code
EmployeeViewModel
public class EmployeeViewModel
{
public bool Monday { get; set; } = false;
//...bool properties for Tuesday through Sunday
public Employee Employee { get; set; }
}
Employee/ _AddEmployeeModalPartial
#model JSarad_C868_Capstone.ViewModels.EmployeeViewModel
#Html.AntiForgeryToken()
<div class="modal modal-fade" id="addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="addEmpoyeeLabel">Add Employee</h4>
<button type=button class="close" data-bs-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Add">
<div class="form-group">
<input asp-for="Employee.Id" class="form-control" />
<input asp-for="Employee.Availability" class="form-control" />
<label asp-for="Employee.Role"></label>
<select asp-for="Employee.Role" class="form-control">
<option value="Bartender">Bartender</option>
<option value="Server">Server</option>
</select>
<span asp-validation-for="Employee.Role" class="text-danger"></span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Name"></label>
<input asp-for="Employee.Name" class="form-control" />
<span asp-validation-for="Employee.Name" class="text-danger"></span>
</div>
#* <div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Phone"></label>
<input asp-for="Employee.Phone" class="form-control" />
<span asp-validation-for="Employee.Phone" class="text-danger">
</span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Email"></label>
<input asp-for="Employee.Email" class="form-control" />
<span asp-validation-for="Employee.Email" class="text-danger">
</span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Address"></label>
<input asp-for="Employee.Address" class="form-control" />
<span asp-validation-for="Employee.Address" class="text-danger">
</span>
</div>
#* <div class="mb-3">*#
<div class="form-group">
<label>Availabiliy</label>
</div>
<div class="row pb-4">
<div class="col">
<div class="form-check">
<input asp-for="Monday" class="form-check-input"
type="checkbox" />
<label asp-for="Monday" class="form-check-label"></label>
</div>
<!--...//form check boxes for Tuesday trough Sunday -->
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary"
data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"
data-bs-save="modal">Save</button>
</div>
</div>
</div>
</div>
EmployeeController.cs
[HttpGet]
public IActionResult Add()
{
EmployeeViewModel viewModel = new EmployeeViewModel();
return PartialView("_AddEmployeeModalPartial", viewModel); ;
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Add(EmployeeViewModel viewModel) //code never reaches this Action
{
viewModel.Employee.Availability = ConvertDaysToChar(viewModel.Employee.Availability)
if (ModelState.IsValid)
{
_db.Employees.Add(viewModel.Employee);
_db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return PartialView("_AddEmployeeModelPartial", viewModel);
}
}
site.js
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-bs-toggle="ajax-modal"]').click(function (event) {
/* event.preventDefault();*/
var url = $(this).data('url');
console.log(url)
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
})
})
PlaceHolderElement.on('click', '[data-bs-save="modal"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
console.log(actionUrl);
var sendViewModel = form.serialize();
console.log(sendViewModel);
//$.post(actionUrl, sendViewModel).done(function (data) {
// PlaceHolderElement.find('.modal').modal('hide');
/*above is the code from a tutorial for modals. It also doesn't send the object to
post action*/
$.ajax({
type: 'POST',
url: actionUrl,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(sendViewModel),
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
})
})
When I click the save button on the model, the console.log(sendViewModel) returns the correct Serialization with all of the properties and their correct names. And the properties change correctly when there is input.
Employee.Id=&Employee.Availability=&Employee.Role=Bartender&Employee.Name=&Employee.Phone=&Employee.Email=&Employee.Address=&Monday=false&Tuesday=false&Wednesday=false&Thursday=false&Friday=false&Saturday=false&Sunday=false
But I get an error "Failed to load resource: the server responded with a status of 404 ()"
and when I check it the page says "No webpage was found for the web address: https://localhost:44313/Add HTTP ERROR 404" as if it's trying to get a post. It is also missing the controller, but if I change my form action to "Employee/Add" in the _Partial view it still doesn't send the data along with the url, which is causing an entirely different problem. I would greatly appreciate any help or guess or input of any kind. I'm about five seconds away from throwing my laptop out the window on this one. Thanks.
1.Remove the #Html.AntiForgeryToken() inside your form,like below:
<form action="Add" >
#Html.AntiForgeryToken()
....
Then after you serialize the form you can get the AntiForgeryToken, like below:
Because when you don't add #Html.AntiForgeryToken()inside form, after you serialize the form you don't get the AntiForgeryToken, like below:
Besides, if you use <form asp-action="Add" > In ASP.Net Core anti forgery token is automatically added to forms, so you don't need to add #Html.AntiForgeryToken(),you can find in the below :
2.change your ajax like below:
$.ajax({
type: 'POST',
url:'/Employee/Add',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: sendViewModel,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
result:
First, I had to change the form action from "Add" to "Employee/Add". ThenI had to remove the antiforgery token from my post action. The first code that is commented out actually works fine otherwise. In my defense I did remove the antiforgery token when I had the wrong URL, but I forgot to retest that when I had the correct one.
Desperately need another set of eyes. This form submission works perfectly on the first submission. But unless I reload the page again it fails. I feel like I've checked everything, the form values are reset fine no matter what in the js but for some reason they do not make it into the Request payload on the second post. Any help is much appreciated.
$scope.submitLogin = function(data) {
var form = $scope.login;
$scope.formerror = '';
$scope.success = '';
if (form.username.length > 0 &&
form.password.length > 0) {
console.log(form.username);
console.log(form.password);
$http.post('/login', form)
.success(function(data) {
$scope.success = data['res'];
$scope.login = [];
window.scrollTo(0, 0);
})
.error(function(data) {
$scope.formerror = data;
});
} else {
$scope.formerror = "something went wrong. Try again.";
}
//$scope.form = new Array({'error':'test', 'msg':''});
}
<form id="login-form" ng-submit="submitLogin()" role="form">
<label for="login_user">username: </label>
<input id="login_user" ng-model="login.username" type="text" name="username" class="form-control" placeholder="username">
<label for="login_password">password: </label>
<input id="login_password" ng-model="login.password" type="password" name="password" class="form-control" placeholder="password">
<input class="btn btn-primary" type="submit" class="btn btn-success btn-send" value="login">
</form>
Hi I am developing web application in angularjs. I have two forms in one html page. Below is the structure.
<form name="form1">
<input type="text" name="fname" />
<input type="text" name="lname" />
<input type="submit" value="Next" />
</form>
<form name="form2">
<input type="text" name="address" />
<input type="text" name="state" />
<input type="submit" value="Next" />
</form>
On clicking on the next submit button of first form i want to validate first form and i want to scroll to second form and disable the first form.
On clicking on the next submit button of form2 i want to validate second form and i want to submit data to server using $http from both forms(form1 and form2).
May i know is this is possible to achieve this? Also may i know is this is the right way i am following or something else i have to do with above requirement? Any suggestion or help would be greatly appreciated. Thank you.
You can bind all your values to a common object. I am enabling the second form after submitting the first form. In second forms submit function, you just have to loop through the values of common object and append it to formData. If you don't have any reason for having two forms, you can consolidate it into one.
Note: I have not added any form validations. For adding form validations, please refer https://codepen.io/sevilayha/pen/xFcdI
HTML:
<form name="form1" ng-submit="enableForm2()">
<input type="text" name="fname" ng-model="obj.fname" />
<input type="text" name="lname" ng-model="obj.lname" />
<input type="submit" value="Next" />
</form>
<form name="form2" ng-show="enableForm" ng-submit="finalSubmit()">
<input type="text" name="address" ng-model="obj.address" />
<input type="text" name="state" ng-model="obj.state" />
<input type="submit" value="Next" />
</form>
JS:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.obj = {};
$scope.enableForm = false;
$scope.enableForm2 = function() {
$scope.enableForm = true;
}
$scope.finalSubmit = function() {
$http({
method: 'POST',
url: YourURL,
withCredentials: true,
headers: {
'Content-Type': undefined
},
data: {},
transformRequest: function(data, headersGetter) {
var formData = new FormData();
angular.forEach($scope.obj, function(value, key) {
formData.append(key, value);
})
return formData;
}
}).then(function(data) {
$scope.enableForm=false;
}).catch(function(data, status) {
})
}
});
You can acheive it vai an Ajax Call not by direct Submit. Moreover Form Submit is not required. (Adding Form tag is optional)
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<!-- Angular Material Library -->
<script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.4/angular-material.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Personal Info</p>
<input type="text" ng-model="form1.fname" name="fname"/>
<input type="text" ng-model="form1.lname" name="lname"/>
<input type="button" ng-click="SubmitForm()" value="Next"/>
<p>Address Info</p>
<input type="text" ng-model="form2.address" name="address"/>
<input type="text" ng-model="form2.state" name="state"/>
<input type="button" ng-click="SubmitForm()" value="Next"/>
</div>
<script>
var app = angular.module('myApp', ['ngMaterial']);
app.controller('myCtrl', function ($scope, $http, $q, HTTPService) {
$scope.form1 = {
fname: '',
lname: ''
};
$scope.form2 = {
address: '',
state: ''
};
$scope.SubmitForm = function () {
let submitFormData = {
form1: $scope.form1,
form2: $scope.form2
};
HTTPService.SubmitData(submitFormData);
}
});
app.factory('HTTPService', function ($http, $q) {
return {
SubmitData: function (formData) {
let apiUrl = 'http://localhost:2000/...';
var req = {
method: 'POST',
url: apiUrl + "SaveData.php",
headers: {
"Content-Type": "application/json",
"Authorization": '',
"Access-Control-Allow-Origin": "*"
},
data: formData
};
var result = $http(req)
.then(function(response) {
return angular.fromJson(response.data);
}, function(response) {
return null;
});
return result;
},
};
});
</script>
</body>
</html>
Using $scope also you will get values of fields which are not in same form.
HTML Code
<div ng-app="App" ng-controller="Ctrl">
<form name="myForm">
<!-- first nested form -->
<div ng-form="form1">
<label><p>Personal Info</p></label>
<input type="text" name="fname" ng-model="myForm.fname"/>
<input type="text" name="lname" ng-model="myForm.lname"/>
</div>
<!-- second nested form -->
<div ng-form="form2">
<label><p>Address Info</p></label>
<input type="text" name="address" ng-model="myForm.address"/>
<input type="text" name="state" ng-model="myForm.state"/>
</div>
<!-- etc. -->
<input type="submit" ng-click="SubmitForm()" value="Next"/>
</form>
</div>
JS/Controller code
var app = angular.module('App');
app.controller('Ctrl', function ($scope) {
$scope.SubmitForm = function () {
var SubmitForm = $scope.myForm;
console.log(SubmitForm);
}
});
You can do someting like below
<form name="form1" ng-submit="moveNext(user)">
<input type="text" ng-model="user.fname" name="fname" required/>
<input type="text" ng-model="user.fname" name="lname" required/>
<input type="submit" value="Next"/>
</form>
<form name="form2" ng-submit="submit(addressData)">
<input type="text" ng-model="addressData.address" name="address"/>
<input type="text" ng-model="addressData.state" name="state"/>
<input type="submit" value="Next"/>
</form>
and in Controller
$scope.userDetails = {};
$scope.addressDetails = {};
$scope.moveNext = function(userData){
$scope.userDetails = userData //Save user Data here and implement logic to scroll to next form and validation
}
$scope.submit = function(addressData){
$scope.addressDetails = addressData;
// and validate the form and Submit data to server here as per your requirement
}
This is my first foray into Google scripts and I have a form that calls two different Google app scripts(both are in the .gs file). One Uploads a file while the other saves the form data to a google spreadsheet. For some reason I get an error when calling the file upload script
(Uncaught TypeError: Cannot read property 'closure_lm_407634' of null)
While the script that uploads the data works fine.
Saving the form data to spreadsheet(which works):
google.script.run.withUserObject(data).saveToSheet(data);
-- which calls:
function saveToSheet(data) {
var date = new Date();
var sheet = SpreadsheetApp.openById(submissionSSKey);
sheet
.appendRow([date, data.name, data.email, data.headline,
data.location, data.newsContent, data.websiteContent, data.expiry, data.fileUrl]);
}
Uploading file(doesn't work):
google.script.run
.withUserObject(theForm)
.withSuccessHandler(processForm)
.uploadFile(theForm);
-- which calls:
function uploadFile(form) {
var folder = DriveApp.getFolderById(folderId), doc = '', file = form.uploadedFile;
if (file.getName()) { doc = folder.createFile(file); }
return doc;
}
I can't for the life of me figure out why one call works while the other does not. I've tried every way I could think of to call the upload script but nothing works. I've tried removing the user object and success handler.
HTML:
<?!= include('styles'); ?>
<div id="container" class="col-lg-12 col-md-12 col-sm-12">
<header class="col-lg-offset-3 col-md-offset-3"></header>
<div class="col-lg-offset-3 col-lg-6 col-md-6 col-sm-12" id="form">
<h1 class="text-center">
SAS News Submission
</h1>
<span id="required-content">
<sup>*</sup>
Required
</span>
<br>
<br>
<form name="sas-form">
<label for="name" class="required">Contact Person/ Source of News</label>
<input type="text" name="name" value="test" class="form-control" id="name" required="required">
<br>
<label for="email" class="required">Contact Person's email (in case we have questions regarding your News content)</label>
<input type="email" name="email" value="me#me.com" id="email" class="form-control" required="required">
<br>
<label for="headline" class="required">Headline (try to keep below 10 words if possible) </label>
<input type="text" name="headline" value="headline" id="headline" class="form-control" required="required">
<br>
<label for="newsContent" class="required">News Content *Note all content must be fully edited to ensure posting</label>
<textarea rows="5" cols="0" name="newsContent" class="form-control" id="newsContent" required="required">
Content
</textarea>
<br>
<label class="required">Where would you like the News to be shared? (You may choose more than one)</label>
<ul id="social-list">
<li>
<input type="checkbox" name="newsletter" id="newsletter" value="newsletter">
<label for="newsletter"> Newsletter</label>
</li>
<li>
<input type="checkbox" name="social" id="social" value="social">
<label for="social"> Social Media (Facebook, LinkedIn, Twitter)</label>
</li>
<li>
<input type="checkbox" name="website" id="website" value="website" checked>
<label for="website"> Website </label>
</li>
</ul>
<br>
<label for="websiteContent">If you chose the website, please provide specific instructions on where you would like the content to be posted.</label>
<br>
<small>News and Events Page, Volunteer Page, Student Page, etc. Ex: Please post in the News and Events Page and send the link and headline out on social media.</small>
<textarea rows="5" cols="0" name="websiteContent" id="websiteContent" class="form-control">website content</textarea>
<br>
<label for="expiry">If your content has an expiration date, please share that date below.</label>
<input type="date" name="expiry" id="expiry" class="form-control">
<br>
<label>If you have files that need to be attached, pick them below.</label>
<input type="file" name="uploadedFile" id="file">
<br>
<div id="not-valid"><span></span></div>
<div id="error"><span>
An error occurred, please try submitting again.
</span></div>
<div id="success"><span>
Form submission was successful! Thank you!
</span></div>
<input type="button" value="Submit" class="btn btn-primary" id="submit"
onclick="validateForm(this.parentNode)">
</form>
</div>
</div>
<footer>
<?!= include('javascript'); ?>
</footer>
<script>
var validateForm = function(theForm)
{
var valid = true;
$('#not-valid span').empty();
$('input').removeClass('warning');
if($('#name').val() == '')
{
$('#name').addClass('warning');
$('#not-valid span').append('Please enter a name <br>');
valid = false;
}
if($('#email').val() == '')
{
$('#email').addClass('warning');
$('#not-valid span').append('Please enter an email <br>');
valid = false;
}
if($('#headline').val() == '')
{
$('#headline').addClass('warning');
$('#not-valid span').append('Please enter a headline <br>');
valid = false;
}
if($('#newsContent').val() == '')
{
$('#newsContent').addClass('warning');
$('#not-valid span').append('Please enter news content <br>');
valid = false;
}
if(!$('#social').is(':checked') && !$('#website').is(':checked') && !$('#newsletter').is(':checked'))
{
$('#not-valid span').append('Please choose where you would like the news to be shared. <br>');
$('#social-list').addClass('warning');
valid = false;
}
if(valid)
{
google.script.run.withSuccessHandler(processForm).uploadFile(theForm)
}
};
function processForm(file)
{
var fileUrl = file ? file.getUrl() : 'No file uploaded',
location = [];
if($('#social').is(':checked'))
{
location.push('social');
}
if($('#newsletter').is(':checked'))
{
location.push('newletter');
}
if($('#website').is(':checked'))
{
location.push('website');
}
var data = {
name: $('#name').val(),
email: $('#email').val(),
headline: $('#headline').val(),
location: location.toString(),
newsContent: $('#newsContent').val(),
websiteContent: $('#websiteContent').val(),
expiry: $('#expiry').val() ? $('#expiry').val() : 'No expiration date selected',
fileUrl: fileUrl
};
google.script.run.saveToSheet(data);
clearForm();
success();
};
var clearForm = function()
{
$("input[type=text], input[type=date], textarea, input[type=email], input[type=file]").val("");
$("input[type=checkbox]").attr('checked', false);
enableSubmit();
};
var success = function()
{
$('#success').show()
};
var enableSubmit = function()
{
$("#submit").prop('disabled', false);
};
</script>
I was able to reproduce your error. I have no idea why that error is occurring, but I found a way to make it work.
Here is what you need to do:
Put an id attribute into the upper form tag:
<form id="myForm">
Remove the button using an input tag.
Add a <button> tag outside of the form. Must be outside of the form. And get the form with document.getElementById('myForm')
<form id="myForm">
<input type="file" name="uploadedFile">
</form>
<button onclick="validateForm(document.getElementById('myForm'))">submit</button>
I've tested this. It got the file, and sent it to the server inside of the form element.
You can use Logger.log() in the server code without using the debugger.
function uploadFile(form) {
Logger.log('form: ' + form);
Logger.log('form.uploadedFile: ' + form.uploadedFile);
Logger.log('form.uploadedFile: ' + form.uploadedFile.getName());
Hi i started learning AngularJs and now im trying to do my Login module using angular and php, but i have some issues. I have watched alot tutorials but none of them was helpful in my case, so here is what i have: controllers.js:
var controllers = angular.module('controllers', []);
controllers.controller('loginController', ['$scope', '$http', 'UserService', function(scope, $http, User) {
scope.main = [
{username: '', password: ''}
]
scope.login = function(){
var config = {
url: '../auth/login.php',
method: 'POST',
data: {
username: scope.main.username,
password: scope.main.password
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}
$http(config)
.success(function(data,status,headers,config){
if(data.status){
//succefull login
User.isLogged = true;
User.username = data.username;
}
else{
User.isLogged = false;
User.username = '';
}
})
.error(function(data,status,headers,config){
User.isLogged = false;
User.username = '';
});
}
}])
auth.js:
var services = angular.module('services', []);
services.factory('UserService', [function(){
var sdo = {
isLogged: false,
username: ''
};
return sdo;
}]);
login.php:
$username = $_POST['username'];
if($username){
return "Logged";
}else{
return false;
}
and the html:
<div class="col-xs-12" id="loginCol" ng-controller="loginController">
<form ng-submit='login()' name="form" novalidate>
<div class="form-group">
<label for="username" class="sr-only">Username</label>
<input type="text" ng-model="scope.main.username" class="form-control" id="username" placeholder="Име..." />
<label for="password" class="sr-only">Password</label>
<input type="password" ng-model="scope.main.password" class="form-control" id="password" placeholder="Парола..." />
</div>
<div class="form-group pull-right">
<button type="button" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-default">Register</button>
</div>
</form>
</div>
In this case i want just if user type something in the username input and hit the login button and on successful call of login.php to return some message. The problem is that code written like that got error "'loginController' is not a function, got undefined" how to fix it?
(Disclosure: I'm one of the developers of UserApp)
You could try the third-party service UserApp, together with the AngularJS module.
Check out the getting started guide, or take the course on Codecademy. Here's some examples of how it works:
Login form with error handling:
<form ua-login ua-error="error-msg">
<input name="login" placeholder="Username"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Log in</button>
<p id="error-msg"></p>
</form>
Signup form with error handling:
<form ua-signup ua-error="error-msg">
<input name="first_name" placeholder="Your name"><br>
<input name="login" ua-is-email placeholder="Email"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Create account</button>
<p id="error-msg"></p>
</form>
ua-is-email means that the username is the same as the email.
How to specify which routes that should be public, and which route that is the login form:
$routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
$routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
The .otherwise() route should be set to where you want your users to be redirected after login. Example:
$routeProvider.otherwise({redirectTo: '/home'});
Log out link:
<a href="#" ua-logout>Log Out</a>
Access user properties:
User info is accessed using the user service, e.g: user.current.email
Or in the template: <span>{{ user.email }}</span>
Hide elements that should only be visible when logged in:
<div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>
Show an element based on permissions:
<div ua-has-permission="admin">You are an admin</div>
And to authenticate to your back-end services, just use user.token() to get the session token and send it with the AJAX request. At the back-end, use the UserApp API with the PHP library to check if the token is valid or not.
If you need any help, just let me know :)
You have created the application
var controllers = angular.module('controllers', []);
but didn't use it in the html code, add ng-app attribute to the wrapper div
<div class="col-xs-12" ng-app="controllers" id="loginCol" ng-controller="loginController">
the second issue, that you try to catch submit event, but don't submit the form, use submit type instead button
<button type="submit" class="btn btn-primary">Login</button>
or add ng-click="login()" attribute to the button and remove ng-submit='login()' from the form