I'm sending POST request with angular with submitted form.
I have optionals input fields and when I type something there and delete it then in my request I have this field containing "".
Is that how it should be?
Thats how my form look:
<label class="col-md-2 col-xs-2 my-label" for="contactFirstName">Imię</label>
<div class="col-md-3 col-xs-3">
<input type="text" class="form-control" id="contactFirstName" name="contactFirstName"
placeholder="Imię"
ng-model="loan.newLoan.contactPerson.firstName" >
</div>
And thats how I'm sending the request:
function create() {
return RequestFactory.save({id1:'loans', id2:'create'},vm.newLoan,
function () {
MessageFactory.setSuccess({show:true, msg:'success'});
$state.reload('loan.new');
}, function(response){
vm.isError = true;
ErrorFactory.errorHandler(vm.errorMessages, response);
});
}
And when sending, in my request json with this field looks like this:
{"firstName":""}
Is that ok? Or there should't be this field in the request if its empty?
What should I do with this?
Is that ok?
Yes or not, depends of what your backend service is expecting.
You can remove the empty fields in Angular by doing something like
function create() {
var data = {};
if (vm.newLoan.contactPerson.firstName) {
data.firstName = vm.newLoan.contactPerson.firstName;
}
RequestFactory.save({ id1: 'loans', id2: 'create' }, data, ...);
}
And you should do a supplementary check in your backend service to remove the empty fields if you don't want to save it. Never trust the data sent from a client, even if you validate the data in JavaScript. Always do an extra check in the server code.
Hence your html input field is not required, it is perfectly fine.Hope your backed service also an optional field.If it's a required field then you have to check as shown below when you press the Save button.
This is just an example:
Html
<button type="submit" class="btn btn-primary blue" ng-
click="vm.save(yourFormName.$valid)"> Save</button>
JS
//to save
vm.save = function (isValid) {
if (isValid) {
//fires save method here
}
};
Related
I want to provide id and date though the html form and then submit these values
to the js controller and execute one of my endpoint with that values (adminId and adminDate). I think something is missing.
// adminForm.html
<form class="form-horizontal" role="form" ng-controller="AdminController">
<input class="form-control" id="adminId" placeholder="adminId" ng-model="formInfo">
<input class="form-control" id="adminDate" placeholder="adminDate" ng-model="formInfo">
<button type="submit" ng-click="adminUpload()" class="btn btn-success">AdminUpload</button>
</form>
// AdminController.js
define([], function() {
function AdminController($scope, $http) {
$scope.adminUpload = function() {
$http.get('/app/endpoint/$scope.adminId/$scope.adminDate').success(
function () {
alert("Something went wrong!");
}
).error(
function () {
alert("Everything fine!");
}
);
};
}
AdminController.$inject = ['$scope', '$http'];
return AdminController;
}
);
There are a few errors in your code, the template, and the controller. I'll list them one by one to explain and provide one example,
The live example
https://plnkr.co/edit/G3f6X0mUVwQ4Nxj2
The Explanation
In Template:
Your ng-model in both inputs are referencing the same model. You should make reference to different elements (or different attributes of the same element). So, I used other elements for the sake of the example.
Your button is type=submit. It's a problem because the submit default behavior is POST the form information (and load the form's action). So, I redefined the button just as a button.
In Controller:
You're not interpolating the string on the request of the URL. You're always fetching '/app/endpoint/$scope.adminId/$scope.adminDate'. You should be fetching '/app/endpoint/(value of $scope.adminId)/( value of $scope.adminDate)'.So I used a template literal (The strings with the back quote symbol)and concatenate the strings with the variable values.
You were using success/error functions in the inverse order. Your success says "Something went wrong!" and your error says "Everything fine!"
Based on AngularJS documentation (https://docs.angularjs.org/api/ng/service/$http), there are no success/error functions after $http.get, so even when they were so used and they were part of AngularJS maybe they aren't in your version. So, my recommendation would be to use the recommendation function which is then(successCallback, errorCallback)
After all this explanation the code would be
template
<form class="form-horizontal" role="form">
<input
class="form-control"
id="adminId"
placeholder="adminId"
ng-model="adminId"
/>
<input
class="form-control"
id="adminDate"
placeholder="adminDate"
ng-model="adminDate"
/>
<button type="button" ng-click="adminUpload()" class="btn btn-success">
AdminUpload
</button>
</form>
controller
$scope.adminUpload = function () {
const url = `/app/endpoint/${$scope.adminId}/${$scope.adminDate}`;
alert(url);
$http
.get(url)
.then(function () {
alert('Everything fine!');
}, function () {
alert('Something went wrong!');
});
};
Can anybody tell How to validate empty text box for mandatory field in button click in angular js after validate i need to call web service call .Can anybody tell how to implement?
Use this:
<form name="yourForm">
<input name="name" ng-model="model.name" type="text" required />
<div ng-messages="yourForm.name.$error">
<div ng-message="required">Name is required!</div>
</div>
<button ng-click="send()">Send</button>
</form>
And in controller js:
$scope.send = function () {
if ($scope.yourForm.$valid) {
// TODO: send model to server
}
}
Don't forget:
Include Angular ngMessages module in your app.
Good luck
You can use 'required' attribute to make sure they enter a value in the field
<input type="text" name="userName" ng-model="user.name" required>
For the service call you can have a javascript method onClick , for example:
<button type="button" class="button" name="Search" id="searchButton" ng-click="getUserInfo()">Search</button>
then you do an ajax call in the Angular module
$scope.getUserInfo = function()
{
if ($scope.fetchData)
{
var data = {
func: "USERINFO",
searchUserId: $('#searchUserId').val()
};
$http({method:'POST',
url:'/MYAPP/getuser',
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(data, status, header, config) {
$scope.users = data;
})
.error(function(data,status, headers, config) {
alert('Error getting user infos ');
})
}
}
This is a quick example. the /MYAPP/getuser maps to a REST service that returns the data in JSON format. The success(function) is what gets executed when the call is executed successfully and the data is returned. You can bind the returned data to an angular table or control for display.
.error is executed if the call fails
As for the REST services, You can write it in JAVA or C# or whatever language you like, as long as it returns JSON.
I am using Angular-Payments that intercepts the form data and submits it to Stripe. This works well, however, I'm not sure how to access form data after its sent to stripe. For example, my form has quantity field which I would like to get access to but I don't know how to...
Here is what I'm doing HTML
<form stripe-form="handleStripe" role="form" ng-if="authenticated" name="takeMoneyForm" ng-submit="takeMoney(takeMoneyForm, model)">
<input type="text" name="card_number" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="takeMoneyForm.number.$card.type">
<input type="text" name="card_cvc" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type">
<input type="text" nam="card_expiry" ng-model="expiry" payments-validate="expiry" payments-format="expiry">
<input type="text" ng-model="quantity"/>
<button class='form-control submit-button btn btn-majoo' type='submit'>Pay »</button>
</form>
JS
$scope.takeMoney = function(formData, model){
$scope.handleStripe = function(status, response){
if(response.error) {
// there was an error. Fix it.
alert("Error happened")
} else {
var dataModel = {
email: model.email,
profile: {
stripe_token: response.id,
stripe_id: model.profile.stripe_id
//here I would like to get access to the quantity from the form
}
}
djangoAuth.takeMoney(dataModel)
$scope.complete = true;
}
}
}
I feel like this should be simple but I'm very new to Angular and can't seem to figure this out.
since youre using ng-model the values of those fields should be on that form's scope(as in scope.number)
If they are not accessible it could be one of two things:
1) Angular Payments clears the ng-model following submit
2) you are trying to access it from a different scope.
I'm trying to code a web page that contains two checkboxes and to send a request to my web server for each check/uncheck. I have to check at server side which checkboxes are checked and which are not to make some specific operations.
Form (snippet of code) :
<form method="get" action="#Url.Action("Index")" data-monitoring-ajax="true" data-monitoring-target="#ListeAlertes">
<input type="checkbox" name="affiche" value="fixees" id="fixees" style="margin-left:40px;margin-right:3px;" checked /> Alertes fixées
<input type="checkbox" name="affiche" value="nonFixees" id="nonFixees" style="margin-left:10px;margin-right:3px;" checked /> Alertes non-fixées
</form>
monitoring.js
$(function () {
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-monitoring-target"));
$target.replaceWith(data);
});
return false;
}
$("form[data-monitoring-ajax='true']").submit(ajaxFormSubmit);
});
Note : I've included monitoring.js into the web page.
Any brilliant idea, please ?
Since the options seem to represent the same item just in a different state, you really only need one checkbox.
The Html
<input type="checkbox" id="enableAlerts" style="margin-left:40px;margin-right:3px;" /> Alertes fixées
The javascript (jQuery)
With this, you can subscribe to the change event to know when to send the request to the server.
$("#enableAlerts").change(function(){
$.post("/Controller/UpdateAlerts",
{ enableAlerts: this.checked },
function(data){ console.log("Successfully saved user options!"); });
});
In the above script we listen for the change event to fire and when it does, we post our data to the server so it can process it. If the server returns a 200 status code, it will write to the console that it was successful. Since only one checkbox is being sent, there isn't any reason to wrap the checkbox in a form and serialize the form to send to the server.
The Server code
Now all you need is a controller/action to call to update the option on the server.
[HttpPost]
public HttpStatusCodeResult UpdateAlerts(bool enableAlerts)
{
//Save to database
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
The above code allows the javascript code to post the data to the server. In this case I allowed the value to be nullable and default to false if so. After that, do what you need to and return a response code so the client-side code can inform the user of the status of their request.
In response to comment by user
In this case wrapping it in a form would be correct. The majority of the steps are similar with minor modifications.
Html
<form method="post" id="filterOptions">
<input type="checkbox" name="Checkbox1" value="true" />
<input type="checkbox" name="Checkbox2" value="true" />
</form>
Javascript
$("#filterOptions input[type='checkbox']").change(function () {
var form = $("#filterOptions").serialize();
$.post("/Controller/AjaxFilteredList",
form,
function (data) { console.log("Retrieved data successfully!") });
});
The Model
public class MyModel
{
public bool Checkbox1 { get; set; }
public bool Checkbox2 { get; set; }
}
The model's property names must match the name of the property, case-insensitive. This is made easier if you make this a ViewModel and pass it into the repective View and use Html.CheckboxFor(m => m.Checkbox1) to render the checkbox.
The controller action
[HttpPost]
public ActionResult AjaxFilteredList(MyModel model)
{
//check you viewmodel's variables to get your list
return PartialView("_FilteredList", filteredList);
}
The above assumes you have a partial view named "_FilteredList" and a variable named "filteredList" in-scope with the results you want to render.
Use .change()
$("form[data-monitoring-ajax='true'] input[type='checkbox']").change(function(){
//make your Ajax Call here and send name of the checkbox or id of the checkobox
});
Attribute Equals Selector [name="value"]
I have a form like this:
<form name="paymentForm" id="paymentForm" action="/submit.jsp" method="post">
<fieldset id="ccData">
<input id="ccNumber" name="ccNumber"/>
</fieldset>
<fieldset id="otherData">
<input id="requestId" name="requestId"/>
</fieldset>
</form>
When you slick submit, I would like to submit(via ajax) only #ccData filedset to some different url (e.g. submitCC.jsp) and based on response I want to submit full form to actual url.
How can I achieve that ?
Use jQuery's serialize method
var formData = $("#ccData").serialize();
$.post("TheUrl",formData);
You could do that with JavaScript - e.g jQuery. You build an eventHandler like
$('#paymentForm').on('click', function () {
$(this).preventDefault();
if ($(this).hasClass('first_send')) {
$.ajax({
url: "your_url",
data: { ccData: $('#ccData').val()}
}).done(function ( data ) {
$('#paymentForm').addClass('first_send')
// examin the data, insert stuff you need and send the form again
// with ajax
})
} else {
$(this).removeClass('first_send')
// this is the second send - so do stuff here - show a result or so
}
})
With the class first_send you can check if it is the first send or the second. This is just an untested, incomplete idea how you could do it. I guess you get the big picture ...