How to update data record using angularJS and Laravel? - angularjs

I'm a beginner and I'm creating a simple CRUD system using AngularJS and Laravel 5. I'm having problems implementing/making the UPDATE feature (to edit data) work. Every time I run it, I keep getting this error on my browser console:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mycrudapp-kkoyao.c9users.io' is therefore not allowed access. The response had HTTP status code 500.*
Here is my code for my html/form:
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-app="addApp" ng-controller="addController">
<h2>Edit Account</h2>
<h4 class="modal-title" id="myModalLabel">Please fill in details</h4>
<div class="modal-body">
<form name="frmAccounts" ng-submit="submitForm(Account.id)" class="form-horizontal" novalidate="">
<div class="form-group error">
<label for="inputEmail3" class="col-sm-3 control-label">Account Holder's Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Enter First and Last Name"
ng-model="Account.acctName" ng-required="true">
<span class="help-inline"
ng-show="frmAccounts.name.$invalid && frmAccounts.name.$touched">Name field is required.</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Bank Account Number</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="acctNum" name="acctNum" placeholder="Enter Bank Account Number"
ng-model="Account.acctNum" ng-required="true">
<span class="help-inline" ng-show="frmAccounts.acctNum.$invalid && frmAccounts.acctNum.$touched">Please check your Bank Account Number.</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Bank Account Type</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="acctType" name="acctType" placeholder="Savings or Checking Account"
ng-model="Account.acctType" ng-required="true">
<span class="help-inline" ng-show="frmAccounts.acctType.$invalid && frmAccounts.acctType.$touched">Please indicate bank account type.</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Bank Account Current Balance </label>
<div class="col-sm-9">
<input type="text" class="form-control" id="acctBalance" name="acctBalance" placeholder="Enter current balance"
ng-model="Account.acctBalance" ng-required="true">
<span class="help-inline" ng-show="frmAccounts.acctBalance.$invalid && frmAccounts.acctBalance.$touched">Check Bank Account Balance</span>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="btn-save" ng-disabled="frmAccounts.$invalid">Save Account</button>
</div>
</form>
</div>
</div>
<script included here, see below>
</body>
</html>
Then here is my AngularJS script (included in the body tag, below of my html page):
<script>
// Defining angularjs application.
var app = angular.module('addApp', []);
// Controller function and passing $http service and $scope var.
app.controller('addController', function($scope, $location, $http, $log, $window) {
var url = $location.absUrl();
$scope.url = $location.absUrl();
$http.get(url + "/api")
.then(function (response) {$scope.Account = response.data;}); //this part is working
$scope.submitForm = function(id) {
// Posting data to php file
$http({
method : 'POST',
url : 'https://mycrudapp-kkoyao.c9users.io/api/accounts/' + id,
data : $scope.Account,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('This is embarrassing. An error has occured. Please check the log for details');
});
});
</script>
The GET Method at the beginning is working fine and the data is fetched and displayed on the forms.
But when I click the "Save" Button to call the submitForm() function in my script, nothing happens and I get the error (see above) on my browser console (Chrome). But this script was edited and came from my CREATE a new entry feature, and was working fine. So I'm not sure what is the problem.
Anyway, here are my Laravel codes:
Laravel Route:
Route::post('/api/accounts/{id}', 'AccountCtrl#update');
Laravel Controller:
public function update(Request $request, $id) {
$account = Account::find($id);
$account->acctName = $request->input('acctName');
$account->acctNum = $request->input('acctNum');
$account->acctType = $request->input('acctType');
$account->acctBalance = $request->input('acctBalance');
$account->save();
}
I think the problem is in my Laravel controller, but not really sure how to fix it.
Also, how do I fix the code for DELETING data?
I'm sorry for this long, messy post, but it is my first time here and I really need help on this. Thank you very much.

Try to add to your web service the next header:
header("Access-Control-Allow-Origin", "*")

This is a CORS problem, probably because your browser is sending a preflight(OPTIONS) request. A quick search: https://github.com/barryvdh/laravel-cors
Edit: The OPTIONS request should return a 200 OK

Related

how to save form data to database in angularjs

I am pretty new in angular.
I'm working on an internal tool where I can get the user details like location, work profile and mobile number etc.
So i have a form with location, work profile dropdowns and mobile number input field. Here for the above fields im already getting data from database through ajax get request. If i want to change data like mobileNumber, how can i do that and how to save that to database which should override the before mobile number. thanks in advance.
here is my html code:
<form name="userForm">
<div class="page-heading fs-xs-1-5">
Update Profile
</div>
<div class= "second-row">
<div class="row">
<div class="col-lg-4">
<label for="Location"> Location</label>
<select class="form-control" placeholder="location" ng-model="user.location" required>
<option value="">Select Location</option>
<option>Hyderabad</option>
<option>Ahmadabad</option>
<option>New Jersey</option>
<option>California</option>
<option>Jaipur</option>
</select>
</div>
<div class="col-lg-4">
<label for="WorkProfile"> Work Profile</label>
<select class="form-control" placeholder="workprofile" ng-model="user.workProfile" required>
<option value="">Select Profile</option>
<option>UI Developer</option>
<option>Tester</option>
</select>
</div>
<div class="col-lg-4">
<label for="ContactNumber"> Contact Number</label>
<input class="form-width contact-height" type="text" ng-model="user.mobileNumber" maxlength="20" required></input>
</div>
</div>
</div>
<div class="third-row">
<div class="row">
<div class="col-lg-4">
<label for="SkillSet"> Skill Set</label>
<textarea id="SkillSet" class="form-width" placeholder="Enter Your skill set here..." row="4" col="100" ng-model="user.skillset" maxlength="250" required></textarea>
</div>
</div>
</div>
<button class="btn btn-primary setng-btn" type="submit" ng-click="addnewdata">Save</button>
</form>
js:`
(function () {
angular
.module('app.login')
.factory('userprofileService', userprofileService);
userprofileService.$inject = ['config', '$http'];
function userprofileService (config, $http) {
var userprofileService = this;
userprofileService.getUserDetails = function(){
return $http({
method: 'GET',
url: config.apiURL+'/v2/user',
headers: { 'Content-Type': 'application/json' }
}).then(function(response){
return response.data;
});
}
`
That will be too much to make clear.
for short, you need REST service as backend to call to save data.
AngularJS project is only front-end, you need backend ( to develop with Nodejs, JSP or asp.net/C# ) to serve this purpose.

AngularJS - Create dynamic email fields and checking and validation

I would like to create a form with several fields: name, last name, ... and add one or several email. The first email field is mandatory. After he should have the possibility to click on "Add email" for adding a new email address. He could add 4 others emails (5 emails in total).
The system should be verify if the format of the email is correct, display a message if necessary and register the data in a DB.
Here my controler "ctrlAddContacts" and module (app.js):
var app=angular.module('ContactsApp', ['ngRoute', 'ui.bootstrap', 'ngDialog']);
app.factory('HttpInterceptor', ['$q', '$rootScope', function($q, $rootScope) {
return {
// On request success
request : function(config) {
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
// On request failure
requestError : function(rejection) {
//console.log(rejection); // Contains the data about the error on the request.
// Return the promise rejection.
return $q.reject(rejection);
},
// On response success
response : function(response) {
//console.log(response); // Contains the data from the response.
// Return the response or promise.
return response || $q.when(response);
},
// On response failure
responseError : function(rejection) {
//console.log(rejection); // Contains the data about the error.
//Check whether the intercept param is set in the config array.
//If the intercept param is missing or set to true, we display a modal containing the error
if (typeof rejection.config.intercept === 'undefined' || rejection.config.intercept)
{
//emitting an event to draw a modal using angular bootstrap
$rootScope.$emit('errorModal', rejection.data);
}
// Return the promise rejection.
return $q.reject(rejection);
}
};
app.controller('ctrlAddContacts', function ($scope, ContactService){
$scope.title="Add a contact";
// Allow to create several fields EMAIL
$scope.emails = [
{
}];
$scope.log = function() {
console.log($scope.emails);
};
$scope.add = function() {
var dataObj = {email:''};
$scope.emails.push(dataObj);
}
$scope.submitForm = function(contact){
if($scope.ContactForm.$valid){
// Send the object to the backend for saving data
ContactService.addNewPerson(contact).success(function(Person){
$scope.ContactForm.$setPristine();
$scope.contact= Person;
});
}
}
});
Here my factory (appService.js)
app.factory('ContactService', function($http){
var factory={};
factory.addNewPerson=function(objContact){
//alert(objContact);
return $http.get('http://myapp/contacts.cfc?method=addNewPerson&jsStruct=' + JSON.stringify(objContact))
};
return factory;
})
The function in the backend (server) retrieves the parameter objContact sent by the backend and executes correctly the query (it's working)
Here my view (manageContact.html)
<h3>{{title}}</h3>
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-title">Person Sheet</div>
</div>
<div class="panel-body">
<form name="ContactForm" class="form-horizontal" role="form" novalidate ng-submit="submitForm(contact)">
<div class="form-group">
<label for="txtLastName" class="col-sm-2 control-label">Last Name *</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="txtLastName" maxlength="100" placeholder="Enter Last Name" required ng-model="contact.LASTNAME">
</div>
</div>
<div class="form-group">
<label for="txtPhone" class="col-sm-2 control-label">Phone Number</label>
<div class="col-sm-10">
<input type="number" class="form-control" name="txtPhone" maxlength="20" placeholder="Enter phone" ng-model="contact.PHONENUMBER">
</div>
</div>
<!---------------- FOR ADDING EMAILS FIELDS ------------ START --->
<div>
<div ng-repeat="email in emails">
<div class="form-group">
<label for="txtEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" name="txtEmail_" maxlength="100" placeholder="Enter Email" ng-model="contact.EMAIL">
</div>
</div>
</div>
<button ng-click="add()">Add Email</button>
</div>
<!---------------- FOR ADDING EMAILS FIELDS ------------ END--->
<div class="error-container"
ng-show="ContactForm.txtEmail.$dirty && ContactForm.txtEmail.$invalid">
<small class="error"
ng-show="ContactForm.txtEmail.$error.required">
Your email is required.
</small>
<small class="error"
ng-show="ContactForm.txtEmail.$error.minlength">
Your email is required to be at least 3 characters
</small>
<small class="error"
ng-show="ContactForm.txtEmail.$error.email">
That is not a valid email. Please input a valid email.
</small>
<small class="error"
ng-show="ContactForm.txtEmail.$error.maxlength">
Your email cannot be longer than 20 characters
</small>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" value="Submit" ng-disabled="ContactForm.$invalid">
Cancel
</div>
</div>
</form>
</div>
</div>
Could you please help me for doing the difference in the name of the 5 fields: txtEmail_1, txtEmail_2 in the controler and the view (when the new field is created).
Kind Regards,
You could try the following for creating dynamic form element name attributes.
<div class="col-sm-10">
<input type="email" class="form-control"
name="txtEmail_{{$index}}" maxlength="100"
placeholder="Enter Email" ng-model="contact.EMAIL">
</div>
<span ng-show="ContactForm['txtEmail_' + $index].$invalid">Enter a valid email</span>

Hidden field with value not being passed to controller - Ionic

working on image uploads with Ionic.
When testing my api post with postman it works great, but couldnt get it working with my app.
Trying to debug, I added this to my form:
<input type="hidden" ng-model="projectData.imageBase64" value="testvalue">
And then in my controller:
$scope.projectData = {};
$scope.storeProject = function(projectData) {
$http.post('http://api.com/api/v1/projects', {
title: projectData.title,
image: projectData.imageBase64,
user_id: $rootScope.currentUser.id
}).success(function(response) {
console.log(response);
}).error(function(response){
console.log(response);
});
};
The response from my API (Laravel) is just returning back all the request data asj JSON.
What this returns is no value or record of the image value being passed through.
If I instead change the hidden field to a text field and manually type something then post the form, it is returned back as having input in the request.
Where am I going wrong?
Note: In the form is:
<form ng-submit="storeProject(projectData)">
<div class="list">
<label class="item item-input item-stacked-label">
<span class="input-label">Name</span>
<input type="text" placeholder="Enter a project name" ng-model="projectData.title">
</label>
<input type="hidden" ng-model="projectData.imageBase64" value="ddd">
<label class="item">
<button class="button button-block button-positive" type="submit">Create Project</button>
</label>
</div>
</form>
And the title gets passed through fine.

Upload images to firebase on form submit using ng-file-upload directive

I'm building a small web app (blog post alike) using AngularJs and Firebase. i implemented the addPost controller earlier and it worked good. After i wanted to add an input file inside the form which already implemented to upload images to firebase on form submit using ng-file-upload directive . As a new in angular i knew that firebase can save images as base64 but i couldn't figur out how to make it work.
Maybe some will say that its repeated question, but believe me i searched allover here i couldent find answer.
Here is my form file :
<div class="container" ng-controller="AddPostCtrl">
<form class="form-horizontal" ng-submit="AddPost(files)">
<fieldset>
<!-- Form Name -->
<legend>Create Post</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="txtTitle">Title</label>
<div class="col-md-4">
<input id="txtTitle" name="txtTitle" ng-model="article.title" type="text" placeholder="placeholder" class="form-control input-md">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="txtPost">Post</label>
<div class="col-md-4">
<textarea class="form-control" id="txtPost" ng-model="article.post" name="txtPost"></textarea>
</div>
</div>
<!-- Images -->
<div class="form-group">
<label class="col-md-4 control-label" for="pictures">Add Pictures</label>
<div class="col-md-4">
<input id="pictures" type="file" ngf-select ng-model="files" name="file"
accept="image/*" ngf-max-size="2MB" ngf-multiple="true" ngf-keep="true" ngf-keep-distinct="true" class="btn btn-primary"/>
<!-- Show image thumb and remove option -->
<span ng-repeat="file in files">
<img ngf-thumbnail="!file.$error && file" class="thumb"> <button class="btn btn-danger" ng-click="file = null" ng-show="file">Remove</button>
</span>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="singlebutton"></label>
<div class="col-md-4">
<input id="singlebutton" ng-disabled="!article.title || !article.post" name="singlebutton" class="btn btn-primary" type="submit" value="Publish" />
</div>
</div>
</fieldset>
</form>
</div>
here is my controller :
angular.module('myApp.addPost', ['ngRoute'])
.controller('AddPostCtrl', ['$scope','CommonProp','$firebase','$location','Upload','$timeout', function($scope,CommonProp,$firebase,$location,Upload,$timeout) {
if(!CommonProp.getUser()){
$location.path('/main');
}
/***** Add data to firebase *****/
$scope.AddPost = function(files) {
var fb = new Firebase("https://hotelboard.firebaseio.com/Articles/");
var title = $scope.article.title;
var post = $scope.article.post;
var user = CommonProp.getUser();
var images = Upload.base64DataUrl(files).then(function(base64Urls){
fb.push({
title: title,
post: post,
emailId: user,
images : base64Urls,
'.priority': user
},function(error) {
if (error) {
console.log("Error:",error);
} else {
console.log("Post set successfully!");
console.log(images);
$location.path('/home');
$scope.$apply();
}
});
});
}
}]);
and here is my GitHub for full project files
https://github.com/SaidThaher/HotelApp
If i get help with this issue , it will be more question regards to the result.
PLEASE HELP
Update :
#danialfarid updated the directive and made my day :)
Upgrade to 8.0.6 and move your fb push here:
Upload.base64DataUrl(files).then(function(base64Urls) {
fb.push({...
images : base64Urls,
},...
});
I updated the code too.
Move your fb push here:
Upload.base64DataUrl(files).then(function(base64Urls) {
fb.push({...
images : base64Urls,
},...
});
Upload.base64DataUrl will convert the files to base64 data url which then can be added to the json to be sent to the server.

Debugging Angular Javascript code, Not showing scope in the Model option of batarang debugger

I can't get the scope of the angularjs in batarang. i spent a lot time on debugging angularjs but i am not able to get the scope. here is the html code
<div data-ng-controller="RegisterCtrl">
<div ng-repeat="error in registerError">
<div class="alert alert-danger animated fadeIn">{{error.msg}}</div>
</div>
<div class="alert alert-danger animated fadeIn" ng-show="usernameError">{{usernameError}}</div>
<div class="alert alert-danger animated fadeIn" ng-show="emailError">{{emailError}}</div>
<h1>Register</h1>
<form ng-submit="register()" class="signup form-horizontal">
<div class="form-group">
<label for="name" class="col-md-4 control-label">Full Name</label>
<div class="col-md-8">
<input id="name" type="text" name="name" placeholder="Full name" class="form-control" ng-model="user.name"/>
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-4 control-label">Email</label>
<div class="col-md-8">
<input id="email" type="email" name="email" placeholder="Email" class="form-control" ng-model="user.email"/>
</div>
</div>
<div class="form-group">
<label for="username" class="col-md-4 control-label">Username</label>
<div class="col-md-8">
<input id="username" type="text" name="username" placeholder="Username" class="form-control" ng-model="user.username"/>
</div>
</div>
<div class="form-group">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-8">
<input id="password" type="password" name="password" placeholder="Password" class="form-control" ng-model="user.password"/>
</div>
</div>
<div class="form-group">
<label for="confirmPassword" class="col-md-4 control-label">Repeat Password</label>
<div class="col-md-8">
<input id="confirmPassword" type="password" name="confirmPassword" placeholder="Password" class="form-control" ng-model="user.confirmPassword"/>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-8">
<button type="submit" class="btn btn-primary">Sign up</button>
or <a ui-sref='auth.login' class="show-login">login</a>
</div>
</div>
</form>
</div>
here is angularjs controller code
'use strict';
angular.module('mean.users')
.controller('RegisterCtrl', ['$scope', '$rootScope', '$http', '$location',
function($scope, $rootScope, $http, $location) {
$scope.user = {};
$scope.register = function() {
$scope.usernameError = null;
$scope.registerError = null;
$http.post('/register', {
email: $scope.user.email,
password: $scope.user.password,
confirmPassword: $scope.user.confirmPassword,
username: $scope.user.username,
name: $scope.user.name
})
.success(function() {
// authentication OK
$scope.registerError = 0;
$rootScope.user = $scope.user;
$rootScope.$emit('loggedin');
$location.url('/');
})
.error(function(error) {
// Error: authentication failed
if (error === 'Username already taken') {
$scope.usernameError = error;
} else if (error === 'Email already taken'){
$scope.emailError = error;
}
else $scope.registerError = error;
});
};
}
]);
Please tell where am i doing wrong.
How do you use batarang? It is a really strange tool. You have to move the pointing arrow, click on "+", select the element then, without clicking anywhere else, expand the scope values.
Another technique is, having started the dev tools (of course), right-click on the element and select "inspect element". Then in the console, you can type angular.element($0).scope() to get the scope of element $0 (the one you inspected).
I found Batarang to be really clunky. Instead I now use ng-inspector (http://ng-inspector.org) which is so much more useful. It shows stuff a lot more clearly I find.
Also a great tip is to use the controller as syntax when you define your controllers by routes. It makes your controller scopes show up named in the debugger, as well as giving you lexical access to parent scopes in your templates. Super handy.
Hope that helps!
The problem has been resolved when i installed mean.io application properly on my system using node package manager. Before this, The issue was because i was using the downloaded version of github repository. Even now It is working perfect than before. I am just beginner in MEAN stack application that's why i could not identified the exact problem and posted it without clear understanding.
Note: Don't use downloaded version of mean.io git repository. Just download or install using Node Packege Manager(npm).

Resources