I know this is a common question , but I am facing problem in this. I am unable to refresh by input fields on button click.
When I am clicking button , the information is sent and added up in a list. So whenever I click it the input fields must get cleared/refresh (not page load).
View:
<div class="input-group">
<span class="input-group-addon" id="reg_input">Name</span>
<input type="text" class="form-control" placeholder="Name" ng-model="ff.Name" required>
</div>
<div class="input-group">
<span class="input-group-addon" id="reg_input">Block</span>
<input class="form-control" id="bl" type="text" ng-model="ff.Block" required>
</div>
<div class="input-group">
<input type="text" class="form-control" id="ip" type="text" ng-model="ff.IP" ng-maxlength="2" style="width: 30px" required>
</div>
<a class="btn btn-md btn-primary" ng-click="getClick(ff)">Add</a>
Is there any refresh predefined in bootstrap button ?
EDIT controller:-
$scope.list = {};
$scope.array_of_Names = [];
$scope.getClick= function() {
$scope.master = angular.copy($scope.ff);
$http.post("url", $scope.list).success(function(data) {
$scope.AllData= data;
$scope.addInfo.Segments.push($scope.list);
$scope.ff.Name = "";
$scope.ff.Block= "";
$scope.ff.IP= "";
$scope.array_of_Names.push($scope.list);
console.log("Segment successfully created");
},function (data, status, headers, config) {
// growl.error("Something went wrong");
});
console.log($scope.master);
};
Just Try it!. All property under $scope.ff will be reset.
$scope.ff={};
And you can apply it in your code part like this:
$scope.list = {};
$scope.array_of_Names = [];
$scope.getClick= function() {
$scope.master = angular.copy($scope.ff);
$http.post("url", $scope.list).success(function(data) {
$scope.ff={};
$scope.AllData= data;
$scope.addInfo.Segments.push($scope.list);
$scope.array_of_Names.push($scope.list);
console.log("Segment successfully created");
},function (data, status, headers, config) {
// growl.error("Something went wrong");
});
console.log($scope.master);
};
EDIT:
$scope.getClick= function() {
$scope.master = angular.copy($scope.ff);
$scope.ff = {};
$http.post("url", $scope.list).success(function(data) {
$scope.AllData= data;
$scope.addInfo.Segments.push($scope.list);
$scope.array_of_Names.push($scope.list);
console.log("Segment successfully created");
},function (data, status, headers, config) {
// growl.error("Something went wrong");
}).error(function(err) {
console.log("Error: ", err);
});
console.log($scope.master);
};
Try then instead of success
$scope.getClick = function(ff){
$scope.master = angular.copy($scope.ff);
$http.post("url", $scope.list).then(function(data) {
$scope.AllData= data;
$scope.addInfo.Segments.push($scope.list);
$scope.ff.Name = "";
$scope.ff.Block= "";
$scope.ff.IP= "";
$scope.array_of_Names.push($scope.list);
console.log("Segment successfully created");
},function (data, status, headers, config) {
// growl.error("Something went wrong");
});
console.log($scope.master);
}
Related
I have a application running with a flask backend and angular frontend. Apparently when a wrong password is entered i want to show a error message. I have tried out ng-show and ng-if both nothing seems to work.
This is the html for my login page -
<div layout="column" layout-align="center center" class="">
<img class="logo" ng-src="assets/images/logo.png">
<h1 class="md-display-2 login-heading">Login to Bassa</h1>
<div layout="row">
<md-input-container>
<label>User name</label>
<input type="text" ng-model="user.user_name"/>
</md-input-container>
<md-input-container>
<label>Password</label>
<input type="password" ng-model="user.password" ng-enter="login()"/>
</md-input-container>
<br>
</div>
<div>
<md-button class="md-raised md-primary" ng-click="login()">Login</md-button>
<md-button class="md-raised md-primary" ng-click="signup()">Signup</md-button>
</div>
And this is the login controller -
(function(){
'use strict';
angular
.module('app')
.controller('LoginCtrl', ['$scope', '$state', 'UserService', LoginCtrl]);
function LoginCtrl($scope, $state, UserService) {
$scope.user = {};
$scope.incorrectCredentials = false;
$scope.login = function(){
UserService.login($scope.user, function(status) {
if (status){
$state.go('home.dashboard');
} else {
$scope.incorrectCredentials = true;
}
});
};
$scope.signup = function() {
$state.go('signup');
};
UserService.removeToken();
}
})();
When the incorrectCredentials becomes true , i want to show a message.
After logging the User service -
var login = function(credentials, cb) {
var $http = $injector.get('$http');
return $http({
method: 'POST',
url: BassaUrl + '/api/login',
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
return str.join('&');
},
data: credentials,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
setToken(response.headers()['token']);
setName(credentials.user_name);
setAuthLevel(response.data.auth);
console.log(response);
cb(true);
}, function(error){
console.log("hello i am here")
cb(false);
});
};
I received a response log -
Object {data: "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final/…ead-protected or not readable by the server.</p>↵", status: 403, config: Object, statusText: "FORBIDDEN"}
It isn't entering the error block , which prevents me from prompting wrong password message.
It was actually my own fault. My custom Interceptor simply swallowed authentication errors.
I am making a test app on MEAN stack and whenever I try to update information in my database regarding the fields, Google chrome throws Connection refused to the Url where I am posting the stuff.
Code for the controller:
(function() {
angular.module('TimeSuck')
.controller('EditProfileController',['Upload','$scope','$state', '$http', function(Upload, $scope, $state, $http) {
$scope.user = localStorage['Userdata'] || undefined
$scope.$watch(function(){
return $scope.file
},function(){
$scope.upload($scope.file);
});
$scope.upload = function(file) {
if(file){
Upload.upload({
url:'api/profile/editPhoto',
method: 'POST',
data: {userId: $scope.user._id},
file: file
}).progress(function(event){
console.log("Uploaded");
}).success(function(data){
}).error(function(error){
console.log(error);
})
}
};
$scope.updateUsername = function() {
var request = {
userId: $scope.user[0]._id,
username: $scope.username
}
$http.post('api/profile/updateUsername', request).success(function(){
console.log("success");
}).error(function(error){
console.log(error);
})
}
$scope.updateBio = function() {
var request = {
userId: $scope.user[0]._id,
bio: $scope.bio
}
$http.post('api/profile/updateBio', request).success(function(){
console.log("success");
}).error(function(error){
console.log(error);
});
}
$scope.post = function() {
console.log("successfully Posted.");
}
and the code for the html is here:
<div class="jumbotron">
<div class="col-sm-8 col-sm-offset-2">
<div class="row"> <div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'"
ngf-accept="'image/*'" >Select</div> </div>
<div class="row">
<input class="form-control" ng-model="username" ng-blur="updateUsername()">
</div>
<div class="row">
<textarea class="form-control" ng-model="Bio" ng-blur="updateBio()"> </textarea>
<button type="submit" ng-click="post()"> Post </button>
</div>
</div>
</div>
I am trying to read and insert excel file data to mysql database table using angularjs( front and) and codeigniter (back end).thanks in advance
included xlsx-reader.js
this is only the excel file read code it is not working.
HTML
<div ng-app="App">
<div ng-controller="PreviewController">
<div class='form-group'>
<label for='excel_file'>Excel File</label>
<button class="btn btn-link" type="file" ng-model="file"ngf-select ngf-change="importToExcel()">
<span class="glyphicon glyphicon-share"></span>ImportExcel
</button>
</div>
</div>
</div>
app.js
(function(undefined) {
App.factory("XLSXReaderService", ['$q', '$rootScope',
function($q, $rootScope) {
var service = function(data) {
angular.extend(this, data);
};
service.readFile = function(file, showPreview) {
var deferred = $q.defer();
XLSXReader(file, showPreview, function(data){
$rootScope.$apply(function() {
deferred.resolve(data);
});
});
return deferred.promise;
};
return service;
}
]);
}).call(this);
controller.js
angular.module('App').controller('PreviewController', function($scope, XLSXReaderService)
{
$scope.showPreview = false;
$scope.importToExcel= function(files) {
$scope.sheets = [];
$scope.excelFile = file[0];
XLSXReaderService.readFile($scope.excelFile, $scope.showPreview).then(function(xlsxData) {
$scope.sheets = xlsxData.sheets;
});
};
}
I just want to asked if there's a better way to improve my user validation codes.
directive.js
angular.module('installApp')
.directive('usernameValidator', function ($q, $timeout, $http) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.username = function(modelValue, viewValue) {
return $http.post('../api/v1/checkUsers', {user: {'username':viewValue}}).then(
function(response){
scope.checkUsers = response.data;
var deferred = $q.defer();
$timeout(function() {
if(scope.checkUsers['status'] == 404){
deferred.reject();
}else{
deferred.resolve();
}
}, 2000);
return deferred.promise;
});
};
}
}
});
accounts.html
<form name="myForm" ng-submit="submit()">
<div>
<label>Username: <input type="text" ng-model="signup.username" name="username" required username-validator>
</label>
<div ng-if="myForm.username.$dirty">
<div ng-messages="myForm.username.$error" class="validation-error">
<div ng-message="required">Username required</div>
<div ng-message="username">Username already in use</div>
</div>
<div ng-messages="myForm.username.$pending" class="validation-pending">
<div ng-message="username">Checking username availability... </div>
</div>
</div>
</div>
<div>
<label>Password: <input type="password" ng-model="signup.password" name="password" required></label>
<div ng-messages="myForm.password.$error" ng-if="myForm.password.$dirty" class="validation-error">
<div ng-message="required">Password required</div>
</div>
</div>
<button type="submit" ng-disabled="myForm.$invalid || myForm.$pending">Submit</button>
</form>
The above code is perfectly working fine, but there is a doubt in my mind on how can I improve it in a better way. I've seen many examples and I noticed they didn't used mostly the if/ else condition. Please help
One thing you could do is try to make your directive reusable.
A good example I found on the internet is coming from Year of moo
angular
.module('yourmodule')
.directive('recordAvailabilityValidator',
['$http', function($http) {
return {
require : 'ngModel',
link : function(scope, element, attrs, ngModel) {
var apiUrl = attrs.recordAvailabilityValidator;
function setAsLoading(bool) {
ngModel.$setValidity('recordLoading', !bool);
}
function setAsAvailable(bool) {
ngModel.$setValidity('recordAvailable', bool);
}
ngModel.$parsers.push(function(value) {
if(!value || value.length == 0) return;
setAsLoading(true);
setAsAvailable(false);
$http.get(apiUrl, { v : value })
.success(function() {
setAsLoading(false);
setAsAvailable(true);
})
.error(function() {
setAsLoading(false);
setAsAvailable(false);
});
return value;
})
}
}
}]);
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
First here's my code
Ok my problem is That when trying to use the registration form it doesn't call the code.
i have examined this several times and cant seem to find a problem i'm using the login script on the same page and that seems just fine.
login.js
$(function() {
// Expand
$("#open").click(function(){
$("div#panel").slideDown("slow");
});
// Collapse
$("#close").click(function(){
$("div#panel").slideUp("slow");
});
// Change Text
$("#toggle a").click(function () {
$("#toggle a").toggle();
});
// Login proccess Start
$('.error').hide();
$(".bt_login").click(function() {
// validate input
$('.error').hide();
var username = $("input#username").val();
if (username == "") {
$("label#username_error").show();
$("input#username").focus();
return false;
}
var password = $("input#password").val();
if (password == "") {
$("label#password_error").show();
$("input#password").focus();
return false;
}
var rememberMe = $("input#rememberMe").val();
// correct data sent
var dataString = 'username='+ username + '&password=' + password + '&submit=Login' + '&rememberMe=' + rememberMe;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "../../inc/files/login.php",
data: dataString,
success: function() {
return false;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#login_form').html("<div id='message'></div>");
$('#message').html("<h2>!</h2>")
.append("<p>Error Details; <br /> Status: ", textStatus, " <br /> Error thrown: ", errorThrown,"</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='cross' src='images/cross.png' />");
});
return false;;
}
});
});
// End login proccess
//Registration Process start
$("bt_register").click(function() {
// validate inpu
$('.error').hide();
var username2 = $("input#username2").val();
if (username2 == "") {
$("label#username2_error").show();
$("input#username2").focus();
return false;
}
// var re = new RegExp("/[^a-z0-9\-\_\.]+/i");
// if(re.test(username2) = true) {
// $("label#username2_error2").show();
// $("input#username2").focus();
// return false;
// }
var password2 = $("input#password2").val();
if (password2 == "") {
$("label#password2_error").show();
$("input#password2").focus();
return false;
}
var email = $("input#email").val();
if (password == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
// correct data sent
var dataString = 'username='+ username2 + '&password=' + password2 + '&submit=Register' + '&email=' + email;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "../../inc/files/login.php",
data: dataString,
success: function() {
return false;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#reg_form').html("<div id='message'></div>");
$('#message').html("<h2>!</h2>")
.append("<p>Error Details; <br /> Status: ", textStatus, " <br /> Error thrown: ", errorThrown,"</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='cross' src='images/cross.png' />");
});
return false;
}
});
});
});
html form calling the Jquery
<div id="reg_form">
<form class="clearfix" action="" >
<h1>Register Here!</h1>
<label class="grey" for="username">Username:</label>
<input class="text-input" type="text" name="username2" id="username2" value="" size="23" />
<label class="error" for="username2" id="usernamename2_error">This field is required.</label>
<label class="error" for="username2" id="usernamename2_error2">Your username contains invalid characters!</label>
<label class="grey" for="email">Email:</label>
<input class="text-input" type="text" name="email" id="email" size="23" />
<label class="error" for="email" id="email_error">This field is required.</label>
<label class="grey" for="password2">Password:</label>
<input class="text-input" type="password" name="password2" id="password2" size="23" />
<label class="error" for="password2" id="password2_error">This field is required.</label>
<input type="submit" name="submit" value="Register" class="bt_register" />
</form>
</div>
Change
$("bt_register").click(function() {
TO
$(".bt_register").click(function(event) {
event.preventDefault();
Second error is if (password == "") { because for .bt_register click event you did not defined password variable.
What you can do is define var password; as global so every click event function can use it.
I have modified your code here is what i did and which is alerting passed string.
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function()
{
var password;
$("#open").click(function()
{
$("div#panel").slideDown("slow");
});
$("#close").click(function()
{
$("div#panel").slideUp("slow");
});
$("#toggle a").click(function ()
{
$("#toggle a").toggle();
});
$('.error').hide();
// Start login proccess
$(".bt_login").click(function(event)
{
event.preventDefault();
$('.error').hide();
var username = $("input#username").val();
if (username == "")
{
$("label#username_error").show();
$("input#username").focus();
return false;
}
password = $("input#password").val();
if (password == "")
{
$("label#password_error").show();
$("input#password").focus();
return false;
}
var rememberMe = $("input#rememberMe").val();
var dataString = 'username='+ username + '&password=' + password + '&submit=Login' + '&rememberMe=' + rememberMe;
alert (dataString);return false;
$.ajax(
{
type: "POST",
url: "../../inc/files/login.php",
data: dataString,
success: function()
{
return false;
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
$('#login_form').html("<div id='message'></div>");
$('#message').html("<h2>!</h2>").append("<p>Error Details; <br /> Status: ", textStatus, " <br /> Error thrown: ", errorThrown,"</p>").hide().fadeIn(1500, function() {
$('#message').append("<img id='cross' src='images/cross.png' />");
});
return false;;
}
});
});
// End login proccess
//Registration Process start
$(".bt_register").click(function(event)
{
event.preventDefault();
// validate inpu
$('.error').hide();
var username2 = $("input#username2").val();
if (username2 == "")
{
$("label#username2_error").show();
$("input#username2").focus();
return false;
}
var password2 = $("input#password2").val();
if (password2 == "")
{
$("label#password2_error").show();
$("input#password2").focus();
return false;
}
var email = $("input#email").val();
if (password == "")
{
$("label#email_error").show();
$("input#email").focus();
return false;
}
// correct data sent
var dataString = 'username='+ username2 + '&password=' + password2 + '&submit=Register' + '&email=' + email;
alert (dataString);return false;
$.ajax(
{
type: "POST",
url: "../../inc/files/login.php",
data: dataString,
success: function()
{
return false;
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
$('#reg_form').html("<div id='message'></div>");
$('#message').html("<h2>!</h2>").append("<p>Error Details; <br /> Status: ", textStatus, " <br /> Error thrown: ", errorThrown,"</p>").hide().fadeIn(1500, function()
{
$('#message').append("<img id='cross' src='images/cross.png' />");
});
return false;
}
});
});
});
</script>
<div id="reg_form">
<form class="clearfix" action="" >
<h1>Register Here!</h1>
<label class="grey" for="username">Username:</label>
<input class="text-input" type="text" name="username2" id="username2" value="" size="23" />
<label class="error" for="username2" id="usernamename2_error">This field is required.</label>
<label class="error" for="username2" id="usernamename2_error2">Your username contains invalid characters!</label>
<label class="grey" for="email">Email:</label>
<input class="text-input" type="text" name="email" id="email" size="23" />
<label class="error" for="email" id="email_error">This field is required.</label>
<label class="grey" for="password2">Password:</label>
<input class="text-input" type="password" name="password2" id="password2" size="23" />
<label class="error" for="password2" id="password2_error">This field is required.</label>
<input type="submit" name="submit" value="Register" class="bt_register" />
</form>
</div>
Instead i suggest you to do this with submit form:
$("#reg_form").children('form').submit(function (e) {
e.preventDefault(); //<------------stops the submission
// validate inpu
$('.error').hide();
var username2 = $("input#username2").val();
if (username2 == "") {
$("label#username2_error").show();
$("input#username2").focus();
return false;
}
var password2 = $("input#password2").val();
if (password2 == "") {
$("label#password2_error").show();
$("input#password2").focus();
return false;
}
var email = $("input#email").val();
if (password == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
// correct data sent
var dataString = $(this).serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "../../inc/files/login.php",
data: dataString,
success: function () {
alert('success.');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#reg_form').html("<div id='message'></div>");
$('#message').html("<h2>!</h2>")
.append("<p>Error Details; <br /> Status: ", textStatus, " <br /> Error thrown: ", errorThrown, "</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='cross' src='images/cross.png' />");
});
return false;
}
});
});
ok
i thik your var dataString is not well formatted
you can try this syntax
data: '{LiveID: "' + Live_ID + '", CategoryID: "' + Category_ID + '"}',
This allowed me to create a label and have it link to a predefined function. Enclude the function within the body of the document and before the label.
<label class="error" for="username2" id="usernamename2_error2">Your username contains invalid characters!
function(open)