How can I pass the information from an input field in the front end(using angularjs) as a JSON object to a server(javascript)?
Basically what I intend to do is take input from a user, and pass it as a query to search a database and return the values.
My controller code:
`app.controller('SearchController',['$scope','$http',function($scope,$http){
$scope.click=function(){
var data=$scope.query1;
$http.post('/credjson',data);
/*$scope.addRowAsyncAsJSON = function(){
$scope.cred.push({ 'query':$scope.query1 });
var dataObj = {
query : $scope.query1,
};
var res = $http.post('/credjson', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
});
res.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
$scope.query1='';*/`
Note: The code in between /* */ was a different attempt at trying this out.
My view code:
`<div style="padding-top:20px" ng-controller="SearchController">
<form name="form1" ng-submit="click()">
<input id="creditq" ng-model='query1' type="text" />
<button id="Search" ng-value='Search'>Search</button><br/><br/>
</form>
</div>`
Just construct your JSON payload and pass it to $http as the second param
data: { query1: $scope.query1 }
and then
$http.post('/credjson',data);
Related
I have a checkbox
<div class="checkbox">
<label>
<input type="checkbox" value="add user" v-model="user.permissions">Add User
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="edit user" v-model="user.permissions">
Edit User
</label>
</div>
the checkbox is v-model on user.permission array
user:{
permissions: []
},
in which when i check a checkbox it will produce a result like this
user:Object
permissions:Array[2]
0:"edit user"
1:"add user"
now when i fetch a data from my backend using axios and put the data on user
editUser: function(id){
let vm = this;
axios.get('api/users/' + id)
.then( response => {
vm.user = response.data.data; //PUT RESPONSE DATA TO USER OBJECT
vm.usersModal = true;
})
.catch( error => {
console.log(error);
});
},
it will produced an output like this
user:Object
created_at:"2018-08-28 03:17:33"
deleted_at:null
email:"aa#gmail.com"
id:3
name:"aa"
permissions:Array[2]
0:Object
created_at:"2018-08-28 03:03:41"
guard_name:"web"
id:2
name:"delete user"
pivot:Object
updated_at:"2018-08-28 03:03:41"
1:Object
created_at:"2018-08-28 03:03:41"
guard_name:"web"
id:3
name:"add user"
pivot:Object
updated_at:"2018-08-28 03:03:41"
updated_at:"2018-08-28 03:17:33"
Now how can I check the checkbox using only v-model user.permission. I used the v-model user.permission because I'm using it on posting a request. However when I fetch it using id the data structure changes.
You will have to modify the fetched response:
editUser: function(id){
let vm = this;
axios.get('api/users/' + id)
.then( response => {
response.data.data.user.permissions = response.data.data.user.permissions.map((item) =>
{
return item.name; // <--- convert the array of objects into array of strings
});
vm.user = response.data.data; //PUT RESPONSE DATA TO USER OBJECT
vm.usersModal = true;
})
.catch( error => {
console.log(error);
});
},
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;
}
});
HTML CODE
<h1 class="popup-title full-width no-margin padding-right source-border-bottom"><span>Enter Employee ID</span></h1>
<div class="bar bar-subheader has-header-text no-border search-txt modal-side-align-search">
<label class="item item-input no-padding no-border asda-txtbox-border search-label txt-box-border">
<input type="search" resizepopup class="txt-box search-txtbox" placeholder="Search with keyword..." ng-model="employeeCode" ng-change="scrolltoTop()" ng-blur="fieldBlur()" id="searchSource" ng-keypress="searchEmployee($event)">
<!--<i class="icon ion-search search-icon"></i> -->
<img class="searchStyle" src="assets/images/search.png">
</label>
</div>
JS CODE
$scope.employeeCode = "";
var dataForService = {
"authToken": "",
empCode: ""
}
$scope.searchEmployee = function(keyEvent){
if (keyEvent.which === 13)
{
console.log("The employee code is "+$scope.employeeCode);
UtilityFactory.showLoading();
dataForService.authToken = authTok; // authTok is generated in another part of the program
dataForService.empCode = $scope.employeeCode;
console.log(JSON.stringify(dataForService));
Factory.webCallEmployee(dataForService).success(function(data, status, headers, config) {
var response = data;
console.log(JSON.stringify(response));
console.log(response.employee.employeeCode);
if (response.responseStatus === "success") {
$timeout(function() {
UtilityFactory.hideLoading();
}, 2000);
}
else{
UtilityFactory.hideLoading();
console.log('This employee is not present in our records');
$ionicPopup.alert({
title: 'Error',
template: 'This employee is not present in our records'
}).then(function(res) {
console.log('Error in else block');
});
}
}).error(function(data, status, headers, config) {
alert(status);
UtilityFactory.hideLoading();
$ionicPopup.alert({
title: 'Error',
template: 'Error statement'
});
});
}
}
JSON DATA
{
"responseStatus":"success",
"employee":{
"employeeCode":"E001",
"employeeName":"ABC",
"employeeMobileNo":"1234567890",
"comCode":"0000029558",
"comName":"Digital Mirror",
"deptCode":"HR"
}
}
I have a factory , from which I am getting the correct response status , for learning sake I am using hard-coded JSON data instead of real service but I have one issue -
In my JSON data the only hardcoded employee no is E001 , but I enter any other value it should go to the error block & give me an error , it is always entering the success block , I mean to say if the employee is not E001 , if i enter say Tom as Employee No , it should go the error block but it is not happening
Also if the employee is present I want to display this employee is present , other "Sorry this employee is not available"
Please refer the image to find what I am to do
I'm fetching maximum salary from Employee table. The JSON retrieves the data properly but why angular does not bind data?
Controller.js
app.controller('AdminCntrl', function ($scope, AdminServices) {
$scope.BtnSubmit = function () {
alert('ok1')
var Bust = AdminServices.Getmax();
Bust.then(function (d) {
$scope.Emp = d.data;
})
}
})
Service.js
app.service('AdminServices', function ($http) {
this.Getmax = function () {
var ss = $http({
url: '/Department/Max',
method: 'Get',
data:JSON.stringify(),
content:{'content-type' : 'application/Json'}
})
return ss;
}
})
Controller
public JsonResult Max()
{
var xxx = db.Employees.OrderByDescending(ww => ww.Salary).First();
return new JsonResult { Data = xxx, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Emp.cshtml
<div ng-controller="AdminCntrl">
<input type="button" class="btn btn-primary btn-sm" value="Min" ng-click="BtnSubmit()" />
<div ng-repeat="Accessor in Emp">
{{Accessor.Id}}
<span style="color:red">{{Accessor.Name}}</span>
</div>
</div>
Fiddler Catch Data
{"Id":11,"Name":"Saleem","Department":"Oracle","Salary":100000.00,"EmpType":"Admin","DataofJoin":"\/Date(1462127400000)\/","DataofBirth":"\/Date(597868200000)\/"}
Is the value of $scope.Empequal to your Fiddler Data?
It appears you're not returning an array which is what ng-repeat is expecting. I'd bet if your Fiddler data was represented as an array:
[{"Id":11,"Name":"Saleem","Department":"Oracle","Salary":100000.00,"EmpType":"Admin","DataofJoin":"\/Date(1462127400000)\/","DataofBirth":"\/Date(597868200000)\/"}]
you'd see it bind.
Alternatively, if you're really not expecting an array then if you replace
<div ng-repeat="Accessor in Emp">
{{Accessor.Id}}
<span style="color:red">{{Accessor.Name}}</span>
</div>
with:
<div>
{{Emp.Id}}
<span style="color:red">{{Emp.Name}}</span>
</div>
You'd have some success
I am using MEAN JS, i am trying to edit the list items on the list page, but it shows the error as below. i have initiated the data using ng-init="find()" for the list and ng-init="findOne()" for individual data.
Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array
HTML
Below i the form inside the controller where it initiates the find() and findOne().
<div ng-controller="OrdersController" ng-init="find()">
<div>
<div class="order-filter">
<div ng-repeat="order in orders">
<form ng-init="findOne()" name="orderForm" class="form-horizontal" ng-submit="update(orderForm.$valid)" novalidate>
<input type="text" class="" ng-model="order.title">
<input type="text" class="" ng-model="order.content">
<div class="form-group">
<input type="submit" value="Update" class="btn btn-default">
</div>
</form>
</div>
</div>
</div>
</div>
Controller
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'orderForm');
return false;
}
var order = $scope.order;
order.$update(function () {
$location.path('orders/' + order._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function () {
Orders.query(function loadedOrders(orders) {
orders.forEach(appendFood);
$scope.orders = orders;
});
};
$scope.findOne = function () {
$scope.order = Orders.get({
orderId: $stateParams.orderId
});
};
You need to check your Orders Service which probably is using $resource to provide your API requests (Orders.query)
It should look something like this:
function OrdersService($resource) {
return $resource('api/orders/:orderId', {
orderId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
The style may be different depending on which version of mean you're using. By default, the $resource query will expect an array of results, but if for some reason you've set "isArray" to false then it will expect an object.
https://docs.angularjs.org/api/ngResource/service/$resource