How to post an array object in ajax call in angularjs - angularjs

I have below JSON response, I have to post that in my ajax call but i don't know how to do that.
JSON response:
{
"iASensorTypePresetRequest": [{
"sensorPresetTypeId": "1",
"min": "30",
"max": "50"
}, {
"sensorPresetTypeId": "3",
"min": "1",
"max": "200"
}, {
"sensorPresetTypeId": "5",
"min": "true",
"max": "NA"
}, {
"sensorPresetTypeId": "6",
"min": "false",
"max": "NA"
}
]
}
I have below code:
var formData = $scope.PresetObject;
var reqHeader = {
method: 'POST',
url: getAPI_URL('221') + $scope.selectedUseCase,
data: formData
};
ajaxService.AjaxCall(SuccessFunction, ErrorFunction, reqHeader);
I have posted objects but i have to post that in array that is 'iASensorTypePresetRequest'
I have written service 'ajaxService' and written functions in it 'SuccessFunction' in success function i have called $http service also I have written error function and calling 'AjaxCall' function of service from controller.
My question is How to post an array containing objects in ajax call?

I use the $http service when communicating with the backend. I recommend placing all your backend connectivity into a service. I call mine datacontext.
this is the link to the $http documentation
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
If your api is RESTful you can use the $resource factory.

Related

mutate the post body before it reaches the server according to the data in the server(Fetch API)

I have a react-redux-form that Post its input data to a JSON in the server called feedback, but before the POST I want to add a new property image:feedback_images/(${feedback.length + 1}).jpg in order to show randomly the images with messages and names... in carousel.
I successfully mutate the body before it reaches the server:
export const postFeedback = (formData) => (dispatch) =>{
var mutatedFeedback = JSON.parse(JSON.stringify(formData)); //This line for changing the object
//from not extensible to extensible
mutatedFeedback.image = `feedback_images/(${feedback.length + 1}).jpg`;
fetch(url + 'feedback', {
method: 'POST',
body: JSON.stringify(mutatedFeedback),
headers: {
'Content-Type': 'application/json'
},
credentials: 'same-origin'
})
}
This is the Feedback array of objects in server:
"feedback": [
//Before mutating the body
{
"firstname": "Anis",
"lastname": "Sina",
"phone": "00000000",
"email": "anis#gmail.com",
"message": "First Feedback",
"id": 1
},
//After mutating the body
{
"firstname": "Daniel",
"lastname": "Scout",
"phone": "00000000",
"email": "daniel#gmail.com",
"message": "Second Feedback",
"image": "feedback_images/(undefined).jpg",
"id": 2
},
]
BUT as you can see there "image": "feedback_images/(undefined).jpg", it's undefined which as you all aware it should be undefined, because I need to get the JSON array from the server before I call it there.
This is my question how I can get the 'feedback' JSON array in order to use it there?
Images folder:
My purpose from doing this

I want to send the meeting invite using angularjs. But facing some issues

I am using the rest api of outlook for sending the request. But when i am calling this with above code, in console i am getting error
unhandled exception
$scope.createEvents = function(){
alert("here");
var url = "https://outlook.office.com/api/v2.0/$metadata#Me/Calendars";
$scope.token = "AQABAAIAAADX8GCi6Js6SK82TsD2Pb7rFu9WBTIi5a6r4Up0vk8NCmPR719K3Uiz7NPUBoT9RwewzSWjPfUIybYn9fVVF2dhQ8b0ObN3oIv5Tq91GwZiTuyBhWZ_s07uDJpCUh40K4Bn2F5eEP9TAp8-5eMY0hfyXb4vIukQwTAe9yXCG75WUS08M7m-_kFbtx-TVq-Y2-SKh8Ut7-v4UQq4NYhlf5LQC1arNbwAZVndfND1vSNGcs1BVJboWd7bcgohHecaR57cAuFav2vfsVEm8n3_IKnlapHzWsyXOw7gXnxTmH2pkfAie0LCiQv8C8nQRnYnLquaWKg6b_ZzTl4ela0EwC9cN74BVMQHFWm6NY1EVM8s-HYevrT8R-WwkAUJXprP40Jp-weLY4-K7vOGk0N0n6fQIeu_WoORIZ18-oKxda6j4XunmrLbWEapQy-Oms9BIAs-AZIVN6Ph1zxQk3CC1bbGK6QkiiL4c2Sgrx_6YoxZt1cMh36pjhbe_TxpC2alk5zJineTK0AZUdGJQWGoy-9fTwtzTbYiaRaV4rispV-q-yiYzpWQ1UWROIPZ5qDq2jlCV7ovTDCWhNd_JgKzzHf-2wANBun9WcX924UVcLkkfvh6XU-QxCo1N6gfGYGUwNNJA1kTZjSyxgKSOAKGxKXz96r5qbtJp34Ci9lEO-PpSeLAL5gHoUOX_PlbM_FO4mLcNEu_fB0Us-5sbV8pKPU-WnfLq3PI8gK3lCi5D_itjesuex1f-o1d1vJ3M4jvx-sgAA";
var add_events = {
"Subject": "Discuss the Calendar REST API",
"Body": {
"ContentType": "HTML",
"Content": "I think it will meet our requirements!"
},
"Start": {
"DateTime": "2016-10-10T18:00:00",
"TimeZone": "Pacific Standard Time"
},
"End": {
"DateTime": "2016-10-10T19:00:00",
"TimeZone": "Pacific Standard Time"
},
"Attendees": [
{
"EmailAddress": {
"Address": "nishanth.singh#subex.com",
"Name": "Nishanth Kumar Singh"
},
"Type": "Required"
}
]
};
$http({
method: 'JSOPN',
url: url,
headers:{
'Authorization':'Bearer '+$scope.token,
'Content-Type': "application/json",
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*'
},
data: add_events
}).Succes(function (response) {
alert("Saved")
});
}
Replace
}).Succes(function (response) {
with
}).success(function (response) {
You have used upper case Success in your code & the spelling is incorrect as well. Let me know once you made this change.
Try to use .then() rather than success() as success() has been deprecated.
Update 1
Since you are using version 1.6, use .then(). success() is deprecated as I said
$http({
method: 'JSOPN',
url: url,
headers:{
'Authorization':'Bearer '+$scope.token,
'Content-Type': "application/json",
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*'
},
data: add_events
}).then(function (response) {
alert("Saved")
});
Update 2
You are now facing CORS issue. for quick fix try chrome plugin.
Get proper header to complete the request or you need to config the server to handle such requests.
change method: 'JSOPN' to
method: 'JSON'

Read from json file angularjs

I had json file that I want to fetch data from it using angularjs 1.6 and I wrote some code in controller. I wanna sort out the properties names of objects in console like this:
['web-desktop','android','ios']
The problem that it returned array of undefined values and wanna to figure it out.
There is json file "data.json":
[
{
"platform": "web-desktop",
"cdn": 4.3673292887e+10,
"p2p": 5.667683381e+09,
"total": 4.9340976268e+10,
"upload": 5.774321084e+09,
"percentage": 12,
"viewers": 1,
"maxViewers": 10,
"averageViewers": 1.5725853094274147,
"trafficPercentage": 69.49888073943228,
"live": "unknown"
},
{
"platform": "android",
"cdn": 1.7035777808e+10,
"p2p": 1.526916976e+09,
"total": 1.8562694784e+10,
"upload": 2.753179184e+09,
"percentage": 9,
"viewers": 1,
"maxViewers": 12,
"averageViewers": 1.416065911431514,
"trafficPercentage": 26.14635154335973,
"live": "unknown"
},
{
"platform": "ios",
"cdn": 2.994960132e+09,
"p2p": 9.6722616e+07,
"total": 3.091682748e+09,
"upload": 3.3788984e+07,
"percentage": 4,
"viewers": 1,
"maxViewers": 3,
"averageViewers": 1.152542372881356,
"trafficPercentage": 4.354767717207995,
"live": "unknown"
}
]
And here is my controller:
'use strict';
var app= angular.module('app');
app.controller('MainController',['$scope', '$http', MainController]);
function MainController ($scope, $http) {
// REQUEST OPTIONS USING GET METHOD.
var request = {
method: 'get',
url: 'data.json',
dataType: 'json',
contentType: "application/json"
};
$scope.arrSeries = new Array;
$http(request)
.then(function onSuccess(jsonData) {
angular.forEach(jsonData, function (item) {
$scope.arrSeries.push(item.platform);
});
console.log($scope.arrSeries);
}).catch(function onError(request) {
console.log("not found");
});
}
It returns in console:
(6) [undefined, undefined, undefined, undefined, undefined, undefined]
Where is the trick?
You need to loop through items in jsonData.data not jsonData directly, like this:
$http(request)
.then(function onSuccess(jsonData) {
angular.forEach(jsonData.data, function (item) {
$scope.arrSeries.push(item.platform);
});
This is because jsonData is the response object that's returned, which looks like this:
response = {
config: {method: "GET", transformRequest: Array(1), transformResponse: Array(1), paramSerializer: ƒ, jsonpCallbackParam: "callback", …},
data: (3) [{…}, {…}, {…}],
headers: ƒ (d),
status: 200,
statusText: "OK",
xhrStatus: "complete"
}
So if you loop on the response directly, you'll loop 6 time trying to get platform from each item (which isn't there). Hence the result you got.
The data that your request returns sits in response.data
response = {
...
data: (3) [{…}, {…}, {…}],
...
}
Hope that helps.

Outlook Rest calling form angularjs

Using outlook I am trying to create event, When i send request using POSTMAN its working fine, But same code in Angularjs its not wotking.
what is wrong with code.
Please help.
$scope.createEvents = function(){
var url = "https://outlook.office.com/api/v2.0/$metadata#Me/Calendars";
//var url = "https://outlook.office.com/api/v2.0/$metadata#me/Calendars";
var add_events = {
"Subject": "Discuss the Calendar REST API",
"Body": {
"ContentType": "HTML",
"Content": "I think it will meet our requirements!"
},
"Start": {
"DateTime": "2016-10-10T18:00:00",
"TimeZone": "Pacific Standard Time"
},
"End": {
"DateTime": "2016-10-10T19:00:00",
"TimeZone": "Pacific Standard Time"
},
"Attendees": [
{
"EmailAddress": {
"Address": "sathish.gopikrishnan#stradegi.com",
"Name": "Sathish Gopi"
},
"Type": "Required"
}
]
};
$http({
method: 'POST',
url: url,
headers:{
'Authorization':'Bearer '+$scope.token,
'Content-Type': "application/json",
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*'
},
data: add_events
}).Succes(function (response) {
alert("Saved")
});
I am getting.
Failed to load resource: the server responded with a status of 406 (Not Acceptable). To solve this problem i am using this code now
$scope.createEvents = function(){
var url = "https://outlook.office.com/api/v2.0/$metadata#Me/Calendars";
//var url = "https://outlook.office.com/api/v2.0/$metadata#me/Calendars";
var add_events = {
"Subject": "Discuss the Calendar REST API",
"Body": {
"ContentType": "HTML",
"Content": "I think it will meet our requirements!"
},
"Start": {
"DateTime": "2016-10-10T18:00:00",
"TimeZone": "Pacific Standard Time"
},
"End": {
"DateTime": "2016-10-10T19:00:00",
"TimeZone": "Pacific Standard Time"
},
"Attendees": [
{
"EmailAddress": {
"Address": "sathish.gopikrishnan#stradegi.com",
"Name": "Sathish Gopi"
},
"Type": "Required"
}
]
};
$http({
method: 'JSONP',
url: url,
headers:{
'Authorization':'Bearer '+$scope.token,
'Content-Type': "application/json",
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*'
},
data: add_events
}).Succes(function (response) {
alert("Saved")
});
After Using Jsonp as method I am getting this error
Uncaught SyntaxError: Unexpected token <
406 Not Acceptable is defined as the following:
The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.
see restapitutorial: http status codes
You send the following Accept header:
'Accept': 'application/json;odata.metadata=minimal'
The server says, it cannot produce this content type. If you got it running using postman, have a look at which accept header you've provided there.
Concerning your second try: jsonp is not an http method/verb (GET, PUT, POST, DELETE, PATCH). I'm not an angularjs expert but in case you need jsonp, there is a method you can call.
JSONP is a quite specific (and somewhat problematic) technique. So as long as you can do that, try to avoid it.
i know its an old post, i've had the same problem and this is the solution if someone falls into the same problem,
you should use https://graph.microsoft.com/v1.0/me/calendar/events as URL
Exemple tested code :
var url = "https://graph.microsoft.com/v1.0/me/calendar/events";
var add_events = {
"Subject": "Title",
"Body": {
"ContentType": "HTML",
"Content": " Exemple"
},
"Start": {
"DateTime": "2010-05-17T18:00:00",
"TimeZone": "UTC"
},
"End": {
"DateTime": "2010-05-17T19:00:00",
"TimeZone": "UTC"
}
};
$http({
method: 'POST',
url: url,
headers:{
'Authorization':'Bearer '+localStorage.getItem('Your Token here'),
'Content-Type':'application/json',
'Accept': 'application/json;odata.metadata=minimal',
'Access-Control-Allow-Origin':'*',
'token_type':'Bearer'
},
data: add_events
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
localStorage.setItem('etat_mytoken', 0);
$window.location.href = url_base+'/'+url_base_v+'/app/assets/views/token.html';
});

$resource and get array

I have an API which returns data with the following form (using tastypie):
{"meta":{
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 4},
"objects": [
{
"id": 1,
"name": "name1",
"resource_uri": "/api/v1/operator/1",
"short_name": "NA1"
},
{
"id": 2,
"name": "name2",
"resource_uri": "/api/v1/operator/2",
"short_name": "NA2"
},
...
]
}
So I thought that to have my resource working, I should have used:
var Operator = $resource('http://127.0.0.1:8080\:8080/api/v1/operator/:operatorId',
{operatorId:'#id'},
{
query: {
method: 'GET',
transformResponse: function (data) {
console.log(JSON.parse(data).objects)
return JSON.parse(data).objects;
},
isArray: true
}
});
But when I set isArray to true : I got the following error:
TypeError: Object #<g> has no method 'push'
If I set isArray to false, I have no error but my object also contains all meta datas for this request...
Not sure I understand correctly this $resource feature
Since $resource automatically converts the JSON string to object, you don't have to do call JSON.parse().
Just do
var Operator = $resource('http://127.0.0.1:8080\:8080/api/v1/operator/:operatorId', {
operatorId: '#id'
}, {
query: {
method: 'GET',
transformResponse: function (data) {
return data.meta.objects;
},
isArray: true
}
});
The json data you are sending is not an array, and the meta property is not something created by angular framework. If you are expecting that it gets deserialized into the objects array you have to return only that part and isArray would work.
For now what #sza mentions to get the array you override query and return data.meta.objects

Resources