I have a form that looks like this:
<form id="myForm" ng-submit="submitForm()">
<select name="ItemName" ng-controller="ItemController">
<option value="" selected disabled>Select</option>
<option ng-repeat="item in items track by $index" value="{{item.Id}}">{{item.Name}}</option>
</select>
<input type="text" name="Description" />
<button type="submit">Submit</button>
</form>
My AngularJS FormController then does the following:
form.controller.js
app.controller('FormController', function($scope, $http) {
$scope.submitForm = function () {
$http({
method: 'POST',
url: '/Path/To/MVC/Action',
data: { json: JSON.stringify($('#myForm').serializeArray()) }
})
.success(function(data) {
console.log('success');
})
.error(function(error) {
console.log('failure);
});
};
});
I want my MVC controller to receive a json string that looks like this:
{
"Name": "some item name",
"Description": "some item description"
}
With serialize(), I got something like:
Name=some%20item%20name&Description=some%20item%20description
...and with serializeArray(), I got something like:
[{
name: "Name",
value: "some item name"
},
{
name: "Description",
value: "some item description"
}]
How do I get the JSON string in the format I'm looking for?
Is this what you are looking for? I am a little unclear with what items is, etc:
https://plnkr.co/edit/IFHNtxS226Hq0cCMJYi1?p=preview
$scope.submitForm = function(formData){
console.warn(formData);
$http({
method: 'POST',
url: '/Path/To/MVC/Action',
data: { json: formData }
})
.success(function(data) {
console.log('success');
})
.error(function(error) {
console.log('failure');
})
}
});
Are you using WebAPI?
You can replace your select for this:
<select id="selectId" type="text" ng-required="true" name="nameOfSelect" class="form-control" ng-model="yourModel.ObjectForThisSelect" placeholder="String Inside you Select"
ng-options="info.Value as info.Text for info in items>
</select>
then you should post back "yourModel" object, this way Angular when posting back will serialize only the selected option value.
Additionally in case you are using WebApi you can check in your WebApiConfig class, Register(HttpConfiguration config) method, that you are formatting Json strings in the desired format: i.e.
var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();
Related
I have a AngularJS app where I take in user input and store it in a painting objects and then send it to my spring boot back-end that will store it to the Mongodb server and return an id, however when I try go POST anything to the server i get an empty response back, even though the object gets stored in the server.
AngularJS code:
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.1/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
<br>
<br>
<br>
URL : <input type="text" ng-model="painting.url"><br>
Artist : <input type="text" ng-model="painting.artist"><br>
ArtistInfo : <input type="text" ng-model="painting.artistInfo"><br>
Title : <input type="text" ng-model="painting.title"><br>
Dated : <input type="text" ng-model="painting.dated"><br>
Medium : <input type="text" ng-model="painting.medium"><br>
Dimensions : <input type="text" ng-model="painting.dimensions"><br>
Credit : <input type="text" ng-model="painting.credit"><br>
<button ng-click="submit()">Post</button>
<pre>{{painting | json}}</pre>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope','$http', function($scope,$http) {
$scope.name = "";
$scope.painting = {
url: '',
artist: '',
artistInfo: '',
title: '',
dated: '',
medium: '',
dimensions: '',
credit: ''
};
$scope.submit = function(){
console.log(JSON.stringify($scope.painting));
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: 'http://localhost:8080/paintings',
data: $scope.painting
}).then(function (response) {
console.log(response);
}, function (response) {
console.log("Error");
console.log((JSON.stringify(response)));
});
//$http.post('http://localhost:8080/paintings', $scope.painting).catch(console.error);
};
}]);
</script>
</body>
</html>
SpringBoot Java POST Method:
#RequestMapping(method = RequestMethod.POST, value = "/paintings")
public String save(#RequestBody Painting painting){
repository.save(painting);
System.out.println("Function called");
return painting.getID();
}
PostMan Response:
Not sure why I'm getting an empty response when I check the console in a browser, even though the server is sending back a response.
I think you need to access the data property of the response,
.then(function (response) {
console.log(response.data);
}
What I ended up doing with the help of #Sajeetharan is edit my backend post request to
#RequestMapping(method = RequestMethod.POST, value = "/paintings")
public ResponseEntity<String> save(#RequestBody Painting painting){
repository.save(painting);
System.out.println("Function called");
JSONObject json = new JSONObject();
json.put("id",painting.getID());
return ResponseEntity.ok(json.toString());
}
I know there is a very similar question asked over here but my object hierarchy is different than the one in that question.
Anyways, I want to store the HTML form input data in to my JavaScript object. Here is my HTML form code:
<form id="newAuction">
<input id="title" name="title" required type="text" value="" />
<input id="edate" name="edate" required type="datetime" value="" />
<input id="minbid" name="minbid" required type="number" value="" />
<button class="btn btn-primary">Submit</button>
</form>
What I want is to get the values of these 3 inputs and store it in my JS object.
I know the proper JSON format needed to post the data to my API. (I tried POSTing with POSTman and I get a status 200, so it works). The proper format is:
{
"auction": {
"Title": "Auction1",
"EDate": "01/01/1990",
"MinBid": 30
},
"productIds": [1,2,3]
}
This is what my JS object looks like:
<script>
$(document).ready(function() {
var vm = {
auction: {},
productIds: []
};
//validation and posting to api
var validator = $("#newAuction").validate({
//assigning values
vm.auction.Title = document.getElementById('title').value;
vm.auction.MinBid = document.getElementById('minbid').value;
vm.auction.EDate = document.getElementById('edate').value;
vm.productIds.push(1);
submitHandler: function () {
$.ajax({
url: "/api/newAuction",
method: "post",
data: vm
})
.done(function () {
toastr.success("Auction Added to the db");
//setting the vm to a new vm to get rid of the old values
var vm = { auction: {}, productIds: [] };
validator.resetForm();
})
.fail(function () {
toastr.error("something wrong");
});
return false;
}
});
});
</script>
As you can see, I am using document.getElementById('title').value; to get the values and assign them but I'm getting the syntax error Expected : Comma expected
Not sure if this matters, but this is inside a .NET MVC5 project.
Move your value assignment set of codes inside submitHandler. Check the syntax of validate() https://jqueryvalidation.org/validate/
//validation and posting to api
var validator = $("#newAuction").validate({
submitHandler: function () {
//assigning values
vm.auction.Title = document.getElementById('title').value;
vm.auction.MinBid = document.getElementById('minbid').value;
vm.auction.EDate = document.getElementById('edate').value;
vm.productIds.push(1);
$.ajax({
url: "/api/newAuction",
method: "post",
data: vm
})
.done(function () {
toastr.success("Auction Added to the db");
//setting the vm to a new vm to get rid of the old values
var vm = { auction: {}, productIds: [] };
validator.resetForm();
})
.fail(function () {
toastr.error("something wrong");
});
return false;
}
});
Now I am able to post subcategory in the following way?
Now The result is
subcategory[] : Healthcare
subcategory[] : education
But I need to get this as string separated by commas?
My html code is
<div id="submitBox">
<form method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);">
<select id="basic" class="selectpicker" data-live-search="true" data-live-search-style="begins" title="Select Your City" v-model="subcategory" name="subcategory[]" multiple>
<option v-for="so in services" v-bind:value="so.name">{{so.name}}</option>
</form>
</div>
My vue js code is
<script>
submitBox = new Vue({
el: "#submitBox",
data: {
subcategory: [],
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['subcategory'] = this.subcategory;
$.ajax({
url: '/post/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status) {
alert("Registration Success")
}
}
});
return false;
}
},
});
</script>
I need to postas data
subcategory : healthcare,education
Can anybody please help me to solve the same?
this.subcategory is an array, you can transform it to a string using join like this :
let services = [
{name: 'Hamburger'},
{name: 'Sandwich'},
{name: 'Hotdog'}
];
submitBox = new Vue({
el: "#submitBox",
data: {
subcategory: [],
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['subcategory'] = this.subcategory.join(',');
console.log(data);
return false;
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="submitBox">
<form method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);">
<select id="basic" class="selectpicker" data-live-search="true" data-live-search-style="begins" title="Select Your City" v-model="subcategory" name="subcategory[]" multiple>
<option v-for="so in services" v-bind:value="so.name">{{so.name}}</option>
</select>
<button>Submit</button>
</form>
</div>
If you only need to join the subcategory array inside a string separated by a comma ,, just use:
data['subcategory'] = this.subcategory.join(',');
Maybe you could find useful to use as data of your jQuery ajax call something like:
data: {"subcategory": this.subcategory}
On my page, I'm rendering form, where data comes from api call
data looks like:
{
"id": 22,
"eventTypeId": 1,
"occuredDate": "2016-05-25T00:00:00",
"title": "event refresh",
"description": "check refresh table",
"studyId": 4,
"statusId": 5,
"severityId": 2,
"priorityId": 3,
"study.id": 4,
"study.name": "Study Y",
"status.id": 5,
"status.name": "Closed"
}
html:
<form style="padding: 15px" ng-submit="submitForm()">
<div class="form-group row">
<div ng-repeat="k in rowKeys | filter: '!id'" ng-model="rowValue">
<label for="rowValue" class="col-sm-2">
{{k | hide:'.name'}}:</label>
<div class=" col-sm-2" >
<input class="form-control rowValue" id="rowValue" ng-model="rowData[k]" ng-disabled="isDisabled()"/>
</div>
</div>
</div>
<button type="submit" class="btn btn-default" ng-if="rowData" >Submit</button>
</form>
My problem is when I edit fields such as "title" or "description", everything works fine, but when I try to edit fields such as "study.name" or "status.name" it just refresh the page and doesn't put any updates. Angular watch works fine and I see in console that value has been updated, so could anybody help me to find my mistake?
My submit function:
$scope.submitForm = function() {
$scope.$watch('rowData', function(newValue, oldValue) {
console.log('being watched oldValue:', oldValue, 'newValue:', newValue);
}, true);
$http({
method : 'PUT',
url : $scope.globalUrl + $scope.id,
data : $scope.rowData //form
})
.then(function (res) {
return res;
})
.then(function (){
$('#table').bootstrapTable('refreshOptions', {
'url': $scope.globalUrl
});
})
};
My load function
$scope.load = function (){
$http({
method: "GET",
url: $scope.globalUrl + $scope.id
}).then(function success(response) {
$scope.rowData = response.data;
}, function error(response) {
console.log("It has happend error in response")
});
}
When you have a dot in your key you need to use bracket notation:
obj['study.name']
Here is a quick example:
https://jsbin.com/fihogu/1/edit?js,console
So I'm trying to set up a post function using Angular. I've got a HTML form which has two text boxes (for user input) and a drop down menu for selecting a number of choices (so the user fills out the form and submits data to server).
Binding the two text boxes is fine but I don't know how to bind the two options in my array as choices in the drop down menu?
(Heres a fiddle:http://jsfiddle.net/gtv7s8h3/2/ )
Form:
<form>
<input type="text" id="name" ng-model="myForm.Title" ng-minlength="5" ng-maxlength="20"> title <br/>
<input type="text" id="name" ng-model="myForm.Content" ng-minlength="5" ng-maxlength="20"> content <br />
<select ng-model="CategoryId" ng-options="item.name for item in CategoryId"></select>
<button ng-click="myForm.submitTheForm()">Submit Form</button>
</form>
Angular POST:
angular.module("myapp", [])
.controller("MyController", function($scope, $http) {
$scope.myForm = {};
$scope.myForm.Title = "";
$scope.myForm.Content = "";
$scope.CategoryId = {
data: [{
id: '316556404cac4a6bb47dd4c7ca2dac4a',
name: 'name1'
}, {
id: '306e3d9a6265480d94d0d50e144435f9',
name: 'name2'
}]
};
$scope.myForm.submitTheForm = function(item, event) {
var dataObject = {
Title : $scope.myForm.Title,
Content : $scope.myForm.Content,
CategoryId : $scope.CategoryId
};
var responsePromise = $http.post("/url", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config) {
console.log(dataFromServer.title);
});
responsePromise.error(function(data, status, headers, config) {
alert("Submitting form failed!");
});
}
});
You're trying to bind the categoryID to you array and your ngOptions expression does not loop through your array. You need to bind the categoryId value to a different model.
Add a model for your categoryID:
$scope.myForm.categoryId = null;
and change your select markup:
<select ng-model="myForm.categoryId" ng-options="item.id as item.name for item in CategoryId.data"></select>