I ma trying to update data in the server using restful api. when i click save buttion . I get the massage that data is updated successfully but It is not saving updating data to the server.
I am passing the function updateop to update the data in the server using ng-submit
<tbody><tr ng-repeat="user in names | filter:filters.search| filter: filters.searchdd | filter:customFilter(unit)">
<td>
{{ user.name }}
<div ng-show="collapsed">
<form name="unitUpdateForm" ng-submit="updateop(user)">
<!-- Name -->
<fieldset class="form-group">
<!-- Name -->
<label >Name</label>
<input ng-model="user.name" placeholder="Name" class="form-control" />
<!-- TODO: Add more attributes -->
<label >Short name</label>
<input ng-model="user.shortName" placeholder="Short name" class="form-control" />
<fieldset class="form-group">
<input type="submit" class="btn btn-primary pull-right"
value="Save" />
</fieldset>
</form>
</div>
</div>
Here is my angular js file where i am calling the function.
$scope.updateop = function(user) {
var apiUrl = "http://localhost:8080/api/organisationUnits/";
console.log(user);
// Setup request
var request = $http({
method: "put",
url: apiUrl + user.id + '.json',
data: user,
});
// Perform request
request.success(function(data) {
// TODO: Some kind of feedback? Angular automatically updates template.
//alert("Update success!");
console.log(data);
//Refreshes the data from db with the newly updated unit
init();
}).error(function(data, status) {
alert("Update error");
init();
});
};
It give me alert update sucess . It is not Updating Data on the server.
Related
I am trying to create a user settings page where a user inputs his/her information, clicks "save", then the page saves the data without clearing the inputted fields or reloading the page. The best example I can think of is the user account settings page on Udemy.
A LOT of the similar questions I've looked at are using php or renders data in a div below the form. I want the data to remain IN the form inputs. I'm using nodejs, express, bodyparser.
<form id="updateAccSettings" action="/account" method="POST">
<div class="form-group">
<label for="address">Address* </label>
<input class="form-control" type="text" name="address" placeholder="Address" required/>
</div>
<div class="form-group">
<label for="address2">Address 2 </label>
<input class="form-control" type="text" name="address2" placeholder=""/>
</div>
<div class="form-group">
<label for="city">City* </label>
<input class="form-control" type="text" name="city" placeholder="City" />
</div>
<div class="form-group">
<input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
</div>
</form>
I've tried this with AJAX
$(document).ready(function() {
$("#updateAccSettings").on("submit", function(e){
e.preventDefault();
var details = $("#updateAccSettings").serialize();
$.post("/account", details, function(data){
$("#updateAccSettings").html(data);
});
});
});
and this
$(document).ready(function () {
$("#updateAccSettings").bind("submit", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/account",
data: $("#updateAccSettings").serialize(),
success: function(){
alert("You've successfully updated your account settings.")
}
});
});
});
And I have this for my app.js
app.post("/account", function(req, res) {
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = {address: address, address2: address2, city: city};
account.push(updateAccount);
console.log("Updated data");
res.redirect("/settings/account");
});
When I clicked save, I get a Cannot read property of 'push' undefined. I tried deleting the var address, var address2, etc and keeping only the console.log which logs whenever I click save but doesn't keep the data in the input. I tried adding onsubmit="return false" as an attribute on the form tag but the console.log doesn't run when I click save so I assume it's not doing anything with the data.
Not sure how to proceed from here. All my other forms use modals or render results in another page.
You're getting the error because you're trying to push onto an undefined variable. Namely in the last section when posted this app.post:
app.post("/account", function(req, res) {
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = {address: address, address2: address2, city: city};
account.push(updateAccount); // error is being thrown here
console.log("Updated data");
res.redirect("/settings/account");
});
Once you have a dummy variable for account, you can send back to the frontend a json response to be read in the form success handler.
Example code: (I haven't tested it)
Backend:
app.post("/account", function(req, res) {
var account = [];
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = { address, address2, city };
account.push(updateAccount); // error is being thrown here
console.log("Updated data");
res.json(updateAccount);
});
Frontend:
$(document).ready(function () {
$("#updateAccSettings").bind("submit", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/account",
data: $("#updateAccSettings").serialize(),
success: function(data){
$('#address').value(data.address);
$('#address2').value(data.address2);
$('#city').value(data.city);
}
});
});
});
You could give each of your form input fields an id (e.g the same as their "name" property)and get their values individually when doing the ajax request as follows (that way you can reinsert the values after the form is submitted):
HTML
<form id="updateAccSettings" action="" method="POST">
<div class="form-group">
<label for="address">Address* </label>
<input class="form-control" type="text" name="address" id="address" placeholder="Address" required/>
</div>
<div class="form-group">
<label for="address2">Address 2 </label>
<input class="form-control" type="text" name="address2" id="address2" placeholder=""/>
</div>
<div class="form-group">
<label for="city">City* </label>
<input class="form-control" type="text" name="city" id="city" placeholder="City" />
</div>
<div class="form-group">
<input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
</div>
</form>
JQuery
$(document).ready(function() {
$("#updateAccSettings").on("submit", function(e){
e.preventDefault();
//get the values of our input fields and store them in local variables
var address = $("#address").val();
var address2 = $("#address2").val();
var city = $("#city").val();
//prepare the data object to send in the ajax request
var params = {"address": address, "address2": address2, "city" : city};
$.ajax({
type: "POST",
url: "/account",
data: JSON.stringify(params),
dataType: "json",
success: function(data){
//the ajax request was successful
//We can do something with the data we get back here.
//Also we can reinsert the values (that were submitted) to the form
$("#address").val(address);
$("#address2").val(address2);
$("#city").val(city);
},
error: function(xhr, status, error) {
//an error occured in the request so handle it here
}
});
});
});
I am new using Angularjs and I am having an issue parsing a JSON response. I have login credentials like Username and password and I am trying to parse it , when user clicks on the login button(). If the name and password matched in the following server , I should get success message. This is the HTML code I am using:
<form ng-submit="loginform()" name="logform"><br/><br>
<tr ng-repeat="logcred in signinfo"></tr>
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username" >
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<a ng-click="reloadPage()" class="navbar-brand" ></a>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="submit()" >Login</button>
</div>
</form>
This is the Javascript code using AngularJS:
app.controller('credientials', function($scope,$http) {
$scope.loginform = function (username, password){
$http.get('http://localhost:3000/loginfo')
.then(
function successCallback(data){
$scope.response = data;
if($scope.username === 'response.username' && $scope.password === 'response.password'){
$scope.signinfo = data.loginfo;
}
else{
console.log("Error");
}
})
});
The HTML is showing the variable $scope.response with the JSON returned by the server, but I don't know how to authentication it properly.
What am I doing wrong?
Any help / advice would be greatly appreciated.
EDIT
Check updated snippet of authentication at client side.
if(userData.username == response.data.username && userData.password === response.data.password){
$scope.signinfo = response.data
}
You will get userData variable from form submit button .. see how i am passing
username and pasword to controller using ng-submit="loginform(logcred)"
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
$scope.loginform = function(userData) {
console.log(userData);
$http.post('https://reqres.in/api/users', userData) // here in post rew i am passing username and password to mock api
.then(function(response) {
//as suggested by you in response u will get username = admin#evol.com password = admin;
console.log(response)
if(userData.username == response.data.username && userData.password === response.data.password){
$scope.signinfo = response.data
}
});
}
});
//**NOTE** in above HTTP call you use your url `http://localhost:3000/loginfo` and in your serverside get the username from the request and check password for that username in your database. If password matches with what you have entered then send success message or user details back to client side.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="credientials">
<form ng-submit="loginform(logcred)" name="logform">
<br/>
<br>
{{signinfo}}
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username">
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<a ng-click="reloadPage()" class="navbar-brand"></a>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary">Login</button>
</div>
</form>
</div>
in above HTTP call you use your url http://localhost:3000/loginfo and in your serverside get the username from the request and check password for that username in your database. If password matches with what you have entered then send success message or user details back to client side.
where should i apply if condition, to match the usercredentials?
You need to check if condition in the server side logic where u fetch data from database. like in your server (i.e. in /loginfo)
if(userpassword == passwordfromDB){
//send success message to client side
}
I am implementing AngularJS on an existing web application that requires a common HTTP POST like you would do without AngularJS.
Does any one have a work around to do that?
i have tried setting action="#" and action="." and just action and then do some jquery to inject a action like this. but nothing works
<script type="text/javascript">
$("form").get(0).setAttribute( "action", "test.html" );
</script>
HERE IS MY FORM AND CODE
//MY FORM
<form name="userForm" ng-submit="submitForm(userForm.$valid)" xt-form novalidate>
<div class="form-group">
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn.$invalid && !userForm.fornavn.$pristine }">
<label class="control-label" for="textinput">Fornavn <span class="star-color">*</span></label>
<input autocomplete="off" type="text" value="<?php echo set_value('fornavn'); ?>" name="fornavn" ng-model="userFormData.fornavn" class="form-control" xt-validate msg-required="Du skal udfylde dit Fornavn" required>
</div>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.efternavn.$invalid && !userForm.efternavn.$pristine }">
<label class=" control-label" for="textinput">Efternavn <span class="star-color">*</span></label>
<input autocomplete="off" type="text" value="<?php echo set_value('efternavn'); ?>" name="efternavn" ng-model="userFormData.efternavn" class="form-control" xt-validate msg-required="Du skal udfylde dit Efternavn" required>
</div>
</div>
<button id="membership-box__payBtn" type="submit" ng-model="userFormData.betaling" name="betaling" class="btn btn-success text-uppercase">Gå til betaling</button>
</form>
//CODEIGNITER CONTROLLER
if (isset($_POST['betaling'])) {
$data['tilBetaling'] = array(
'oprettelse' => $this->input->post('oprettelse'),
// 'medlemskab' => $this->input->post('medlemskab'),
'tilBetaling' => str_replace(',', '.', $this->input->post('tilBetaling')),
'pr_maaned' => $this->input->post('pr_maaned'),
'start_date' => $this->input->post('start_date'),
'til_dato' => $this->input->post('til_dato'),
'pakke' => $this->input->post('pakke'),
'type' => $this->input->post('medlemskabTypeFinal'),
'getCenter' => $this->input->post('getCenter'),
'medlemskabPakkePID'=> $this->input->post('medlemskabPakkePID'),
'ekstraInput' => $this->input->post('ekstraInput'),
'periode_price' => $this->input->post('periode_price'),
'kampagneTag' => $this->input->post('kampagneTag'),
// 'header' => $this->input->post('header'),
);
//Gem array til session
$_SESSION['betaling'] = $data['tilBetaling'];
}
If you want to do a normal submit, you can handle ngClick in your controller:
HTML
<div ng-controller="ctrl">
<form name="userForm" action="user/add" method="post">
Name: <input name="name" ng-model="user.name" />
...
<button ng-click="onSubmit(userForm)">Submit</button>
</form>
</div>
JS
app.controller('ctrl', function($scope) {
$scope.onSubmit = function(form) {
if (form.$valid) {
var e = document.getElementsByName(form.$name);
e[0].submit();
}
}
});
An Alternative Solution
As an alternative, consider leveraging services, and redirecting after a successful POST in AngularJS.
HTML
<div ng-controller="ctrl">
<form name="userForm" ng-submit="onSubmit(user)">
Name: <input name="name" ng-model="user.name" />
...
<button type="submit">Submit</button>
</form>
</div>
JS
app.factory('UserService', function($http) {
return {
addUser: function(user) {
return $http({method:'POST', url:'api/user/add', data: user });
}
}
});
app.controller('ctrl', function($scope, $location, UserService) {
$scope.onSubmit = function(user) {
if ($scope.userForm.$valid) {
UserService.addUser(user).success(function() {
$location.path('/user/addSuccessful')
});
}
}
});
Even if you do an AngularJs submit, the request does not go to server. The control still remains on client side. Then you can post the data/form etc through $http service. You can inject $http service in your controller. as
app.controller('reviewCtrl', ['$http', function($http){
$scope.addReview = function(product){
//use $http service here
// Simple POST request example (passing data) :
$http.post(' / someUrl ', {msg:' hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}]);
note: please review the syntax before running the code.
To submit the Angular Js form ONLY after Angular validations are through or passed, you must use reviewForm.$valid flag chack in ng-submit.
With this flag check, the form will not get submitted until all validations are passed.
<form name="reviewForm" ng-controller="reviewCtrl" ng-submit="reviewForm.$valid && reviewCtrl.addReview(product)" novalidate>
....
....
</form>
im trying to validate my users inputs and it works greate that the user can press the submit btn and it errors the input fields that is missing so the user know what input he is missing.
My problem is that it only works when i remove action="/buy" method="post" but i need it to normal submit the form when there is no errors.
How can i do that?
Im using this form validation with angularjs validate http://www.brentmckendrick.com/code/xtform/
<form name="userForm" ng-submit="submitForm(userForm.$valid)" xt-form novalidate>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn.$invalid && !userForm.fornavn.$pristine }">
<label class="control-label" for="textinput">Fornavn <span class="star-color">*</span></label>
<input autocomplete="off" type="text" value="<?php echo set_value('fornavn'); ?>" name="fornavn" ng-model="fornavn" class="form-control" xt-validate required>
</div>
<button id="membership-box__payBtn" type="submit" name="betaling" class="btn btn-success text-uppercase">Go to payment</button>
</form>
Well you can use the $http service to send any type of request to server. When you actually do form post data is posted with content-type:'application/x-www-form-urlencoded'.
For your request if you can set the correct content-type and encode the object to send correctly, it would work. See this fiddle i created earlier that sends data to server as standard form post.
http://jsfiddle.net/cmyworld/doLhmgL6/
The relevant $http request looks like
$scope.update = function (user) {
$http({
method: 'POST',
url: 'https://mytestserver.com/that/does/not/exists',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function (data) {
var postData = [];
for (var prop in data)
postData.push(encodeURIComponent(prop) + "=" + encodeURIComponent(data[prop]));
return postData.join("&");
},
data: user
});
You can model your input fields, and delegate each field to your model as:
<form name="userForm" ng-submit="submitForm(userForm.$valid)" xt-form novalidate>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn.$invalid && !userForm.fornavn.$pristine }">
<input autocomplete="off" type="text" name="fornavn" ng-model="fornavn.input1" class="form-control" xt-validate required>
</div>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn2.$invalid && !userForm.fornavn2.$pristine }">
<input autocomplete="off" type="text" name="fornavn2" ng-model="fornavn.input2" class="form-control" xt-validate required>
</div>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn3.$invalid && !userForm.fornavn3.$pristine }">
<input autocomplete="off" type="text" name="fornavn3" ng-model="fornavn.input3" class="form-control" xt-validate required>
</div>
<button id="membership-box__payBtn" type="submit" name="betaling" class="btn btn-success text-uppercase">Go to payment</button>
</form>
And in your controller, send data using $http as:
var baseUrl=<yourBaseUrl>;
var url = baseUrl+'/buy';
var data = $scope.fornavn;
if(!$scope.userForm.$invalid){
$http.post(url, data).
success(function(data) {
if (data.error_msg) {
alert(data.error_msg);
}else{
alert("Successful! ");
}
}).
error(function(data) {
alert('error');
});
}
I have a form that I created and I want to send that form information to a backend database called Parse.com. I create the table in Parse with the same names as the fields on the form, but I'm not sure how to send it to Parse using js.
<form id="contact-form" class="contact-form" method="post" action="" onSubmit="return checkMail()" name="validation">
<div class="form-group row" id="price">
<div class="col-lg-4">
<input type="text" name="fname" class="form-control" id="name" placeholder="First *" required >
</div>
<div class="col-lg-4">
<input type="text" name="lname" class="form-control" id="name" placeholder="Last *" required>
</div>
<div class="col-lg-4">
<input type="text" name="email" class="form-control" id="name" placeholder="E-mail *" required>
</div>
</div>
</div>
<div class="form-group row" align="center">
<div class="col-lg-12" align="center">
<button type="submit" class="button default">SEND <i class="glyphicon glyphicon-send"></i></button>
</div>
</div>
Attach your parse object save function to the form submit. This can be achieved with ease by using JQuery.
Next you have to capture the form input data, then save it to your Parse object.
This script assumes you have created a class in parse with the [string] columns of fname, lname and email.
<script>
Parse.initialize("API KEY", "JAVASCRIPT KEY");
var ParseObj = Parse.Object.extend('myClass'); //create local parse object from your Parse class
$('#contact-form').submit(function(e) {
//on form submit
e.preventDefault();
//get data from form
var data = {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val()
};
//create new Parse object
parseObj = new ParseObj();
//match the key values from the form, to your parse class, then save it
parseObj.save(data, {
//if successful
success: function(parseObj) {
alert(parseObj.get('fname') + " " + parseObj.get('lname') + " " + parseObj.get('email') + " saved to Parse.")
}
,
error: function(parseObj, error) {
console.log(parseObj);
console.log(error);
}
}
);
});
</script>
This is a typical "too broad" question, as you're not really having a specific problem but just asking us to write the code for you. Best I can do is point you to the parse.com user guide which shows you how you can do this. Check it out, try it for yourself and then ask here again if you have specific issues with the code.
Example snipped from the user guide found here: https://parse.com/docs/js_guide#objects-saving
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.set("score", 1337);
gameScore.set("playerName", "Sean Plott");
gameScore.set("cheatMode", false);
gameScore.save(null, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});