Not getting JSON object. AngularJS - angularjs

I am new in Angular and trying to POST data , but I am getting undefined status. My JSON raw body is like this :
{
"Name": "Something",
"Description": "Something",
"Data": []
}
Name and description is from user input field and Data will be used later to push another JSON object in the array.
I tried but not getting exact output.
Controller:-
app.controller('postController', ['$scope', '$http', 'appService', function ($scope, $http, AppService) {
$scope.addInfos = [{
Name: $scope.name,
Description: $scope.description,
Data: []
}];
$scope.Create = function () {
$scope.addInfos.push({
'Name': $scope.Name,
'description': $scope.Description,
'Data': []
});
$scope.dataObj = {
Name: $scope.name,
Description: $scope.description,
Data: []
};
$http({
method: 'POST',
url: 'http://192.120.27.8:2000/api/Add',
data: $scope.dataObj
}).then(function (data, status, headers, config) {
alert("success");
console.log(data + $scope.Name + $scope.Description);
}, function (data, status, headers, config) {
alert("error");
});
$scope.name = '';
$scope.Description = '';
};
HTML page :-
<div class="input-group col-md-10">
<span class="input-group-addon" id="reg_input" >Name</span>
<input type="text" class="form-control" placeholder="" ng-model="addInfos.name">
</div>
<div class="input-group sepH_b col-md-10">
<span class="input-group-addon" id="reg_input" >Description</span>
<textarea name="reg_textarea" id="reg_textarea" cols="10" rows="3" class="form-control" ng-model="addInfos.description"></textarea>
</div>
<div class="col-md-4">
<a style="" class="btn btn-md btn-primary" ng-click="Create(addInfos)">Create</a>
</div>
The output which I can see in my console is [object Object]. What mistake am I doing here ?
NOTE:- Here I didn't mentioned Data: field as it will be predefined array as of now like this {data:[]} need to inject and pass Name and Description in JSON as I mentioned above.
SECOND also I need to push this over all output data to the Service to store for further use.

Thanks guys , now I can able push necessary datas inside the JSON I did second work around .
$scope.addInfos = {Data: []};
$scope.Create = function() {
$http({
method : 'POST',
url : 'http://192.120.27.8:2000/api/Add',
data : $scope.addInfos
}).success(function(data, status, headers, config) {
growl.success("Created a new File");
console.log(data);
},function (data, status, headers, config) {
growl.error("Something is wrong");
});
};
My second concern is still there , now how to push these data to a service. var something =[];?

Related

The data alone is missing when I try to send from Angular.js to Node.js

I am trying to send data from my Angular.js controller to Node.js backend. I succeeded in making a MongoDB entry when the request is raised.But the data is missing in the MongoDB entry. I am stuck and can't proceed with my app anymore. Can anyone give me a clear explanation why I am not able to send the form data to the Node.js.
I had put my schema of the data here:
var common = require('../common');
var inviteeSchema = common.Schema({
email: String
});
var Invite = common.conn.model('Invite', inviteeSchema);
module.exports = Invite;
I have enclosed the routing code here.
router.route('/addtoinvitelist').post(function (req, res, next) {
var invite =new Invite(req.body);
invite.save(function(err,email){
if(err) throw err;
res.json({message:"your mail id is stored in our database we will soon send you an invite"})
});
});
My HTML form goes here
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="name#mail.com" ng-model="useremail" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(useremail)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
my angular service functions goes here
`this.AddToInviteList = function (email, cb) {
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}, // set the headers so angular passing info as form data (not request payload)
data:"email"
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}`
Controller function is here
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.email = {};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
});
Pass email as json object { 'email' : email }.
Just try this code:
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
Controller :
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
$scope.user = {
email : $scope.useremail
};
UserServices.AddToInviteList($scope.user, function (dataresponse) {
console.log(dataresponse);
})
}
});
In server side you can access the email by calling 'req.body.email'
Change your model name in HTML input element with email and send request as
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/json'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
and get it at backend side as
req.body.email
I think that should work!
Update
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}

How to call ajax on onchange dropdown by angularjs?

My question is
By deafult I am getting result for 1st hotel, how to get results on onchange of hotels dropdown by using angularjs directives ?
My Code
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app='myApp' ng-controller='HttpController'>
{{detail.name}} <br/>
{{detail.address}} <br/>
{{detail.country}}<br/>
</div>
<script>
var hotelid=$('select#hotel_property option:selected').val();
var data = {};
data.Hotelid = hotelid;
data.Action = "hotel_property";
var helloApp = angular.module("myApp", []);
helloApp.controller("HttpController", function($scope, $http) {
$http({
method: 'POST',
datatype:"json",
header: {
"contentType": 'application/json'
},
data: JSON.stringify(data),
url: '/ajax',
}).success(function(data, status, headers, config) {
$scope.detail = data.hotel_details;
}).error(function(data, status, headers, config) {
alert( "failure");
});
});
</script>
<select id="hotel_property">
<option value="111">Taj hotel</option>
<option value="222">oberoi</option>
<option value="333">JW marriot</option>
<option value="444">Grand Maratha</option>
</select>
By deafult I am getting result for 1st hotel, how to get results on onchange of hotels dropdown by using angularjs directives ?
You'll have to do something on these lines.
Use ng-options to populate hotel list
Use ng-model to bind the selected value to some variable
Use ng-change to trigger a function to handle the change.
<select id="hotel_property" ng-model="selectedHotel"
ng-change="fetchInfo(selectedHotel)"
ng-options="hotel.name for hotel in hotels">
<option value="">-- please select -- </option>
</select>
and your controller might look like this.
Defile $scope.hotels with array of hotel id and name.
define a function to fetch hotel information.
helloApp.controller("HttpController", function($scope, $http) {
$scope.hotels = [{
id: 111,
name:'Taj hotel'
},{
id: 222,
name:'oberoi'
},{
id: 333,
name:'JW marriot'
},{
id: 444,
name:'Grand Maratha'
}];
$scope.fetchHotelInfo(hotel){
var data = {};
data.Hotelid = hotel.id;
data.Action = "hotel_property";
$http({
method: 'POST',
datatype:"json",
header: {
"contentType": 'application/json'
},
data: JSON.stringify(data),
url: '/ajax',
}).success(function(data, status, headers, config) {
$scope.detail = data.hotel_details;
}).error(function(data, status, headers, config) {
alert( "failure");
});
}
});
(Copy pasting code might not work)
Hope this helps!
You can use ng-model directive to store the selected value in the scope and use ng-change to fire the ajax query with the model value as parameter.
https://docs.angularjs.org/api/ng/directive/select

Problems using $http POST

I am new in angular.js and I need to make form with 2 fields for numbers and when I click on submit i need to send to server with json for request result of suma. It will look like: 4 in first field , 4 in second field and on submit it will return result 8.
Thanks guys. Here is code:
<div ng-app="app" ng-controller="HttpGetController">
<p>Num1
<input type="number" name="num1" ng-model="num1" required />
</p>
<p>Num2:
<input type="number" name="num2" ng-model="num2" required />
</p>
<button ng-click="SendData()">Saberi</button> <hr />
{{ PostDataResponse }}
</div>
JS
var app = angular.module("app", []);
app.controller("HttpGetController", function ($scope, $http) {
$scope.SendData = function () {
var data = $.param({ num1: $scope.num1, num2: $scope.num2 });
var config = { headers : { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' } }
$http.post('localhost:3000', data, config)
.success(function (data, status, headers, config) {
$scope.PostDataResponse = data;
})
}
});
Get the input values and that will be automatically bind to scope. In your controller, just add those two operands.
$scope.sum = $scope.op1 + $scope.opt2;
then post the $scope.sum to server using $http.post() or thru $resource service.
$http POST with JSON Data Example
app.controller("HttpGetController", function ($scope, $http) {
$scope.SendData = function () {
var data = { num1: $scope.num1, num2: $scope.num2 };
$http.post('https://httpbin.org/post', data)
.then(function (response) {
$scope.PostDataResponse = response.data.data;
})
}
});
The DEMO on PLNKR

Angularjs calling restful api (post) without success bad request

I have to call a restful API with basic auth "i think the auth is working)"
that needs this special custom header: "X-AppGlu-Environment: staging" I don't know how to put the header" then I need to post to one URL, data with this format:
Body:
{
"params": {
"stopName": "what you want search"
}
}
Let's see my code at moment "it's not structured yet"
controller:
'use strict';
angular.module('myApp', ['base64'])
.controller('transportController', function($scope, $http, $base64){
$scope.$watch('search', function() {
fetch();
});
function fetch(){
var data = {
"params": {
"stopName": $scope.search
}
}
$http.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
var encoded = $base64.encode("xxxx:xxxx");
$http.defaults.headers.common.Authorization = 'Basic ' + encoded;
$http.post("the url", data)
.then(function(response){ $scope.details = response.data; });
}
});
view:
<div class="input-group search-bar">
<input type="text" ng-model="search" ng-model-options="{ debounce: 800 }" onclick="select()" class="form-control" placeholder="Enter destiny" autofocus />
<span class="input-group-addon bar-style"><i class="glyphicon glyphicon-search"></i></span>
I receive a error 400 bad request when i try to search for something, i think is something with the format of the object i'm trying to send, but if is, i don't know what to change.
Is working now i changed to this structure
function fetch(){
var data = {
"params":{
"stopName": "%"+$scope.search+"%"
}
}
var encoded = $base64.encode("xxxx:xxxx");
$http({
url: "url",
headers : {
"X-AppGlu-Environment":"staging",
"Authorization": "Basic "+encoded,
"Content-Type" : "application/json; charset=utf-8"
},
method: 'POST',
data: {
"params":{
"stopName": "%"+$scope.search+"%"
}
}
}).then(function(response){
$scope.details = response.data.rows;
});
// $http.get("http://www.omdbapi.com/?s=" + $scope.search)
//.then(function(response){ $scope.related = response.data; });
}

Understanding $scope mechanics in Angularjs

I can't clarify for myself how to deal with $scope in Angularjs. Although I've resolved my current issue other way, still I need help to get comprehension of $scope usage.
I have the following form (simplified for this example). Index.html:
<form class="form-horizontal" ng-controller="AddItemController as addItemCtrl">
<fieldset>
<legend>New item</legend>
<div class="form-group">
<label for="submittedBy" class="col-lg-2 control-label">Submitted by</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="submittedBy" ng-model="addItemCtrl.item.submitted_by" placeholder="Your name here">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<!--button class="btn btn-default">Cancel</button-->
<button type="submit" class="btn btn-primary" ng-click="addItemCtrl.addItem()">Submit</button>
</div>
</div>
</fieldset>
</form>
app.js:
app.controller("AddItemController", ['$scope','$http', function ($scope, $http) {
$scope.item = {};
this.addItem = function() {
$http({
url: "add_item",
method: "GET",
params: this.item
}).
success(function(data, status, headers, config) {
var table = angular.element($("#body")).scope();
table.items = data;
});
**this.item={};**
}
}]);
All I want is to get data from the form, send it to the server, get response, update table and then clear the form. The last part is my issue. I am currenly using this.item={} to handle it. But I do want to call it using $scope, so it should be $scope.item={} and then I want to move it inside addItem function. Unfortunately it's not working for either case.
I have this code and it is working as intended, but it seems I just got lucky/unlucky to make it without understanding mechanism.
app.controller('ItemController', ['$scope','$http', function ($scope, $http) {
function getItems(){
$http({
url: "get_items",
method: "GET"
}).
success(function(data, status, headers, config) {
$scope.items = data;
});
}
getItems();
}]);`
UPDATE. This is how my AddItemController looks like at the moment:
app.controller("AddItemController", ['$scope','$http', function ($scope, $http) {
$scope.item = {};
this.addItem = function() {
$http({
url: "add_item",
method: "GET",
params: this.item
}).
success(function(data, status, headers, config) {
$scope.$$prevSibling.items = data;
$scope.addItemCtrl.item={};
});
}
}]);
It works like I wanted it to. But I don't like $scope.$$prevSibling.items = data; statement, I use it to refresh table which is handled by ItemController, is there a more elegant way to do that?
You don't have to make getItem function, you can just write $http code and it will just work fine, about $scope, just don't use this, it's kind of tricky here, all the variables you want to make just make it with $scope and get it from $scope like this
$scope.item;
$scope.item.getItem = function(){};
var item1 = $scope.item;
And so on.

Resources