Unable to pass the uploaded file name into the angularjs - javascript

We are working on form where user can upload 4 different photos. when i click choose file, it is calling to upload.php file and storing that file into uploadfiles directory.
but after file is uploaded unable to passing that particular file name to the angularjs.
Here is the UI Code
<head>
<script src="add-customer.js"></script>
<script type="text/javascript" src="angular-file-upload.js"> </script>
</head>
<body data-ng-cloak data-ng-app="AddCustomerApp" data-ng-controller="AddCustomerController as parentCtrl">
<section id="container">
<section id="main-content">
<section class="wrapper">
<div class="row mt">
<div class="col-lg-12">
<div class="form-panel">
<h4 class="mb">Add Customer</h4>
<form class="form-horizontal" role="form" id="AddCustomerForm" name="AddCustomerForm" autocomplete="off" enctype="multipart/form-data" novalidate="" data-ng-submit="AddCustomerData(AddCustomer)">
<div class="form-group">
<div class="col-sm-4">
<label for="firstname">First Name</label>
<input class="form-control" type="text" id="firstname" name="firstname" required placeholder="First Name" autofocus data-ng-model="AddCustomer.firstname">
</div>
</div>
<div controller="ChildController as childCtrl">
<div class="form-group" >
<div class="col-sm-6">
<label for="photo">Aadhaar Front</label>
<input type="file" class="form-control" id="adarfront" name="adarfront" required placeholder="Aadhaar Front" data-ng-model="AddCustomer.adarfront" ng-file-select="onFileSelect($files)">
</div>
<div class="col-sm-6">
<label for="photo">Aadhaar Back</label>
<input type="file" class="form-control" id="adarback" name="adarback" required placeholder="Aadhaar Back" data-ng-model="AddCustomer.adarback" ng-file-select="onFileSelect($files)">
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="photo">Other ID Photo Front</label>
<input type="file" class="form-control" id="otheridfront" name="otheridfront" required placeholder="Other ID Photo Front" data-ng-model="AddCustomer.otheridfront" ng-file-select="onFileSelect($files)">
</div>
<div class="col-sm-6">
<label for="photo">Other ID Photo Back</label>
<input type="file" class="form-control" id="otheridback" name="otheridback" required placeholder="Other ID Photo Back" data-ng-model="AddCustomer.otheridback" ng-file-select="onFileSelect($files)">
</div>
</div>
</div>
<button type="submit" class="btn btn-theme" data-ng-disabled="AddCustomerForm.$invalid">Add</button>
</form>
</div>
</div>
</div>
</section>
</section>
</section>
</body>
Here is the AngularJs Code
var AddCustomer = angular.module("AddCustomerApp", ['angularFileUpload','ui.bootstrap'])
AddCustomer.controller("AddCustomerController", function ($scope, $timeout, $http, jsonFilter)
{
$scope.PersonalDetails = true;
var logResult = function (data, status, headers, config)
{
return data;
};
$scope.AddCustomerData = function (AddCustomer)
{
if($scope.AddCustomer.firstname==undefined || $scope.AddCustomer.adarfront==undefined || $scope.AddCustomer.adarback==undefined || $scope.AddCustomer.otheridfront==undefined || $scope.AddCustomer.otheridback==undefined)
{
alert("All fields are mendatory");
$scope.PersonalDetails = true;
$scope.WarningAlert = data;
}
else
{
$http.post('add-customer-process.php',{'firstname':$scope.AddCustomer.firstname,'adarfront':$scope.AddCustomer.adarfront,'adarback':$scope.AddCustomer.adarback,'otheridfront':$scope.AddCustomer.otheridfront,'otheridback':$scope.AddCustomer.otheridback})
.success(function (data, status, headers, config)
{
if(data=="Success")
{
$scope.PersonalDetails = true;
$scope.SuccessAlert = "Data added successfully";
$scope.AddCustomer = {};
$scope.AddCustomerForm.$setPristine();
$scope.AddCustomerForm.$setUntouched();
}
})
.error(function (data, status, headers, config)
{
$scope.WarningAlert = logResult(data, status, headers, config);
});
}
$scope.switchBool = function (value) {
$scope[value] = !$scope[value];
};
};
});
AddCustomer.controller('ChildController',function ($scope, $http, $upload)
{
$scope.parentCtrl.childCtrl = $scope.childCtrl;
$scope.onFileSelect = function($files)
{
$scope.message = "";
for (var i = 0; i < $files.length; i++)
{
var file = $files[i];
console.log(file);
$scope.upload = $upload.upload({
url: 'upload.php',
method: 'POST',
file: file
}).
success(function(data, status, headers, config)
{
$scope.message = data;
$scope.message=$scope.message.replace('\"', '');
$scope.childCtrl.message=$scope.message.replace('\"', '');
})
.error(function(data, status)
{
$scope.message = data;
});
}
};
});
kindly help Us. I'm newbie to AngularJS. Thank you in Advance.

Related

How to create an object in this format

I'm trying to create an object to be sent in an AJAX request in the format I need.
In the code I'm able to get the name attribute for each input element and its value, but I need to create an object in the below format. How can I create that?
{
"userrole":"",
"userAttributes":{
"username":"alks",
"useraddress":"ajdaa",
"usercity":"lajsdk"
}
}
<div class="data-fields-container">
<div class="input-type" data-attr-name="userrole">
<input type="text" name="userrole">
</div>
<div class="input-type" data-attr-name="username">
<input type="text" name="username">
</div>
<div class="input-type" data-attr-name="useraddress">
<input type="text" name="useraddress">
</div>
<div class="input-type" data-attr-name="usercity">
<input type="text" name="usercity">
</div>
</div>
<button id="submit_data">Submit</button>
$(document).ready(function() {
$('#submit_data').on('click', function() {
$('.data-fields-container > .input-type').each(function() {
dataobj = {};
var attrkey = $(this).attr('data-attr-name');
var attrval = $(this).find('input').val();
})
$.ajax(function() {
url: "https://map.net/api/v44",
data: dataobj,
type: 'POST',
dataType: 'Json',
success: function(data) {
console.log('successful')
},
error: function(request, error) {
console.log('failed')
}
})
})
})
You could map the serializeArray() result and construct your object like:
$(document).ready(function() {
$('#submit_data').on('click', function() {
var dataobj = {userrole: $('[name="userrole"]').val()};
var attr = $('.data-fields-container input:not([name="userrole"])').serializeArray().map(function(o) {
this[o.name] = o.value;
return this;
}.bind({}))[0];
dataobj['userAttributes'] = attr;
console.log(dataobj);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data-fields-container">
<div class="input-type" data-attr-name="userrole">
<input type="text" name="userrole">
</div>
<div class="input-type" data-attr-name="username">
<input type="text" name="username">
</div>
<div class="input-type" data-attr-name="useraddress">
<input type="text" name="useraddress">
</div>
<div class="input-type" data-attr-name="usercity">
<input type="text" name="usercity">
</div>
</div>
<button id="submit_data">Submit</button>
dataObj = {
"userrole":document.querySelector('div.input-type input[name="userrole"]').value,
"userAttributes":{
"username":document.querySelector('div.input-type input[name="username"]').value,
"useraddress":document.querySelector('div.input-type input[name="useraddress"]').value,
"usercity":document.querySelector('div.input-type input[name="usercity"]').value
}
}
You don't need to iterate through the inputs since your JSON format is static.

AngularJS 1.6.8: Form data not submitting and so hence unable to save it to localStorage

I have a contact form. On submission, it displays a success message and it should store that data to $localStorage.
But, Form data not is not submitting as I do not see submitted form data in response under network in dev tools and hence I am unable to save it to $localStorage.
below is the code for respective files.
link to plunker
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService) {
var vm = this;
vm.saveform = function(){
var name= vm.name;
var email= vm.email;
var query= vm.query;
console.log(name);
console.log(email);
console.log(query);
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted.";
$scope.user = userService;
};
$scope.navigate = function(home){
$state.go(home)
};
};
//localStorage code
function userService(saveform) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
There are no errors in console.

How to bind the title of a form using Angularjs?

I am creating a form using angularjs and phpmailer. The input fields are binding and sending correctly, however, i am struggling to grab the title of the form, which is pretty important as the form will be a "service type" request.
HTML:
<div ng-controller="ContactCtrl">
<form ng-submit="submit(contactForm)" name="contactForm" method="post" class="service-form form-horizontal" role="form">
<h3 ng-model="formData.serviceName" id="serviceName">Request for {{ details.name }}</h3>
<div class="form-group" ng-class="{ 'has-error': contactForm.inputName.$invalid && submitted }">
<input ng-model="formData.inputName" type="text" class="inputText text-input" id="inputName" placeholder="Name" required>
</div>
<div class="form-group" ng-class="{ 'has-error': contactForm.inputEmail.$invalid && submitted }">
<input ng-model="formData.inputEmail" type="email" class="inputText text-input" id="inputEmail" placeholder="Email" required>
</div>
<div class="form-group" ng-class="{ 'has-error': contactForm.inputMessage.$invalid && submitted }">
<textarea ng-model="formData.inputMessage" rows="4" id="inputMessage" name="inputMessage" placeholder="Please add your requirements as per the 'Best Practice Checklist'"></textarea>
</div>
<button class="btn default btn-cancel" type="submit" onclick="switcher()">Cancel</button>
<button class="btn default" type="submit">Send</button>
</form>
<p ng-class="result">{{ resultMessage }}</p>
</div>
JS:
.controller('ContactCtrl', ['$scope', '$http', function($scope, $http) {
'use strict';
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData;
$scope.submitButtonDisabled = false;
$scope.submitted = false;
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
var request = {
method: 'POST',
url: '/forms/contact.php',
data: $.param($scope.formData),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
$http(request).then(function(data) {
console.log(data);
if (data) {
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result = 'bg-success';
$scope.resultMessage = 'Thanks for the message! We will be in touch very soon.';
$scope.formData = {};
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result = 'bg-danger';
$scope.resultMessage = 'Ooops! Something went wrong, Please fill out all the fields.';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Ooops! Something went wrong, Please fill out all the fields.';
$scope.result = 'bg-danger';
}
}
}]);
so currently, I've got an h3 and have tried several other options, but the details.name isn't sending out, any help on this would be much appreciated. TIA.

Angular JS $modal dismiss causing broken links?

I am using a $modal in angular and, after a simple cycle of creating the modal and dismissing it, the main controller breaks with:
TypeError: object is not a function
at http://localhost:1337/bower_components/angular/angular.min.js:178:79
at f (http://localhost:1337/bower_components/angular/angular.min.js:195:177)
at h.$eval (http://localhost:1337/bower_components/angular/angular.min.js:113:32)
at h.$apply (http://localhost:1337/bower_components/angular/angular.min.js:113:310)
at HTMLAnchorElement.<anonymous> (http://localhost:1337/bower_components/angular/angular.min.js:195:229)
at http://localhost:1337/bower_components/angular/angular.min.js:31:225
at r (http://localhost:1337/bower_components/angular/angular.min.js:7:290)
at HTMLAnchorElement.c (http://localhost:1337/bower_components/angular/angular.min.js:31:207)
The main controller logic looks like:
(function(){
var app = angular.module('butler-user', ['ui.bootstrap']);
app.controller('UserController', ['$http', '$log', '$state', '$modal', '$scope', 'UserStatusService', function($http, $log, $state, $modal, $scope, UserStatusService) {
var self = this;
self.flash = '';
self.users = [];
self.newUser = {};
self.editUser = {};
$http.get('/user')
.success(function(data, status, headers, config) {
self.users = data;
})
.error(function(data, status, headers, config){
console.log('error getting data from /user');
$log.error("Error in get from /user: '"+config+"'");
});
var CreateUserModalCtlr = function ($scope, $modalInstance, userForm) {
$scope.userForm = {};
$scope.submitted = false;
$scope.validateAndCreate = function () {
console.log('Entering validateAndCreate()');
$scope.submitted = true;
if ($scope.userForm.$valid) {
console.log('Creating user with:'+JSON.stringify(self.newUser));
$http.post('/register', self.newUser)
.success(function(data, status, headers, config) {
console.log('response from /register'+data+' status:'+status)
if (status == 200) {
self.newUser = {};
$scope.submitted = false;
$http.get('/user')
.success(function(data, status, headers, config) {
self.users = data;
})
.error(function(data, status, headers, config){
$log.error("Error in get from /user: '"+config+"'");
});
$modalInstance.close('closed');
} else {
self.flash = 'Error creating new user';
}
})
.error(function(data, status, headers, config) {
console.log('Error in /register:'+status);
$modalInstance.close('closed');
});
}
};
$scope.cancelModal = function () {
console.log('Entering cancelModal()');
$modalInstance.dismiss('cancel');
};
};
self.addUser = function () {
var modalInstance = $modal.open({
templateUrl: '/admin/partials/CreateUser.html',
controller: CreateUserModalCtlr,
scope: $scope,
resolve: {
userForm: function () {
return $scope.userForm;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
The modal template looks like:
<div class="modal-header">
<h3>Create New User</h3>
</div>
<div class="modal-body">
<form name="userForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : userForm.firstName.$invalid && submitted }" >
<label>First Name</label>
<input name='firstName' class="form-control" type='text' ng-model='userCtlr.newUser.firstName' required ng-minlength=1>
<p ng-show="userForm.firstName.$invalid && submitted" class="help-block">First name is required.</p>
</div>
<div class="form-group" ng-class="{ 'has-error' : userForm.lastName.$invalid && submitted }">
<label>Last Name</label>
<input name='lastName' class="form-control" type='text' ng-model='userCtlr.newUser.lastName'required ng-minlength=1>
<p ng-show="userForm.lastName.$invalid && submitted" class="help-block">Last name is required.</p>
</div>
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }">
<label>Username</label>
<input type="email" name="username" class="form-control" ng-model="userCtlr.newUser.username">
<p ng-show="userForm.username.$invalid && submitted" class="help-block">Enter a valid email address.</p>
</div>
<div class="form-group" ng-class="{ 'has-error' : userForm.username2.$invalid && !userForm.username2.$pristine }">
<label>Confirm Username</label>
<input type="email" name="username2" class="form-control" ng-model="userCtlr.newUser.username2">
<p ng-show="userForm.username2.$invalid && !userForm.username2.$pristine && submitted" class="help-block">Enter a valid email address.</p>
</div>
<div class="form-group" ng-class="{ 'has-error' : userForm.password.$invalid && !userForm.password.$pristine }">
<label>Password</label>
<input type="password" name="password" class="form-control" ng-model="userCtlr.newUser.password" required ng-minlength=8>
<p ng-show="userForm.password.$error.minlength && submitted" class="help-block">Password is too short.</p>
</div>
<div class="form-group" ng-class="{ 'has-error' : userForm.password2.$invalid && !userForm.password2.$pristine }">
<label>Confirm Password</label>
<input type="password" name="password2" class="form-control" ng-model="userCtlr.newUser.password2" required ng-minlength=8>
<p ng-show="userForm.password2.$error.minlength && submitted" class="help-block">Password is too short.</p>
</div>
<br><br>
{{registerCtlr.flash}}
</div>
<div class="modal-footer">
<button type="button" class="btn"
data-ng-click="cancelModal());">Cancel</button>
<button class="btn btn-primary"
data-ng-click="validateAndCreate();">Create User</button>
</div>
The main HTML page looks like:
<div clas='row' ng-controller='UserController as userCtlr'> <!-- Use bootstrap grid layout -->
<div class="col-md-8">
<table class='table table-striped'>
<thead>
<td>Email Address</td><td>First Name</td><td>Last Name</td>
</thead>
<tr ng-repeat='user in userCtlr.users'>
<td> <a ng-click='userCtlr.editUser(user)'>{{user.emailAddress}}</a></td>
<td> {{user.firstName}}</td>
<td> {{user.lastName}}</td>
</tr>
<tr>
</tr>
</table>
<form name='userForm' ng-submit='userCtlr.addUser()' novalidate>
<input type='submit' value='createNewUser'/>
</form>
</div>
</div>
I am new to the $modal (and Angular in general). I suspect that somehow dismissing the modal is breaking the main controller (or its variables), but I don't understand enough of how this all works to grog what I did wrong.
Any help is appreciated,
Charlie

Update textfield value with ajax data using angular js

I am using angular js directives for bootstrap. What i am trying for is to create an edit form on bootstrap modal when user clicks on edit button from list of items. Here is my code:
HTML:
<div class="modal-header">
<h3>Edit Template</h3>
</div>
<div class="modal-body">
<form name="form" class="form-horizontal" novalidate>
<fieldset>
<div class="span4" ng-class="smClass" ng-show="etemplate.status">{{etemplate.status}}</div>
<div class="control-group">
<label class="control-label" for="etemplateName">Name</label>
<div class="controls">
<input class="input-xlarge" id="etemplateName" ng-model="eTemplate.name" maxlength="150" type="text" required />
</div>
</div>
<div class="control-group">
<label class="control-label" for="etemplateDesc">Description</label>
<div class="controls">
<textarea id="templateDesc" id="etemplateDesc" ng-model="eTemplate.desc"></textarea>
</div>
</div>
<div class="center">
<input type="text" style="display:none;" ng-model="eTemplate.id" value="{{eTemplate.id}}" required />
<button type="button" ng-click="update(eTemplate)" class="btn btn-primary" ng-disabled="form.$invalid || isUnchanged(eTemplate)">Submit</button>
<button class="btn" ng-click="cancel()">Cancel</button>
</div>
</fieldset>
</form>
</div>
Controller:
controller('TemplateController', ['$scope', '$http', '$modal', function($scope, $http, $modal) {
var tmpId = '';
$scope.openEdit = function(id) {
tmpId = id;
var editTmpModalInstance = $modal.open({
templateUrl: 'editTemplateContent.html',
controller: 'ETModalInstance'
});
$http({
method: 'GET',
url: adminBaseUrl+'/get_template/',
params: {'id': tmpId}
}).
success(function(data, status, headers, config) {
$scope.$broadcast('EditTemplateDataReached', data);
}).
error(function(data, status, headers, config) {
});
}
}]).
controller('ETModalInstance', ['$scope', '$http', '$modalInstance', function($scope, $http, $modalInstance) {
$scope.emaster = {};
$scope.smClass = '';
$scope.eTemplate = {};
$scope.$on('EditTemplateDataReached', function(data) {
$scope.eTemplate = data;
$scope.$apply();
});
$scope.isUnchanged = function(eTemplate) {
return angular.equals(eTemplate, $scope.master);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
$scope.update = function(eTemplate) {
var strng = $.param(eTemplate);
};
}]).
My work around for achieving this is when user clicks on edit button id of selected item is passed in my controller which sends an ajax request to server and then fill the fields with respective values. However my fields are not populated when ajax data is returned.
Found the problem in my code i was using $scope for broadcasting and catching the data whereas i have to use $rootScope.
Wrong:
$scope.$broadcast('EditTemplateDataReached', data);
$scope.$on('EditTemplateDataReached', function(data) {
$scope.eTemplate = data;
$scope.$apply();
});
Correct:
$rootScope.$broadcast('EditTemplateDataReached', data);
$rootScope.$on('EditTemplateDataReached', function(e, data) {
$scope.eTemplate = data;
$scope.$apply();
});

Categories

Resources