Unable to get JSON from asmx Web Service in AngularJS - angularjs

I am unable to parse a json file from a asmx webservice.
Here is my WebMethod:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetDataJSON()
{
//var dt = GetCubeResult("");
var _DbConn = Helper.GetDBConnection();
var _CubeConn = Helper.GetCubeConnection();
var _query = Helper.GetWebConfig("dashboard_config");
Data[] datArray = new Data[1];
Data data = GetTilesAsDataArray(_query, _DbConn);
datArray[0] = data;
System.Web.Script.Serialization.JavaScriptSerializer serializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
/*
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type,Accept,Origin,X-Requested-With");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
*/
Context.Response.Write(serializer.Serialize(datArray));
}
and here is my AngularJS Code
app.controller('jsonServerBox', ['$scope', '$http', function($scope, $http) {
$http({
method: 'POST',
crossDomain: true,
contentType: "application/json; charset=utf-8",
url: 'myasmx.asmx/getjson',
data: '[]',
dataType: 'json',
xhrFields: {
withCredentials: true
},
cache: 'false',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/json; charset=utf-8'
}
//url: 'serverbox.json'
}).success(function (data) {
//var myjson = JSON.parse(data);
//$scope.ocw = myjson;
//$scope.ocw = JSON.parse(data);
$scope.ocw = data;
$scope.loading = false;
})
.error(function(data, status) {
console.error('Repos error', status, data);
//alert("schlecht");
});}]);
I already try it with parse and other methods, but no one is working - is there any error in my webservice ? with a local json file the angular code is working.
EDIT: Its working now. I changed my angular Code to following:
app.controller('jsonServerBox', ['$scope', '$http', function($scope, $http) {
$http.get("myasmx.asmx/get",
{
params: {
format: "json",
cache: "false"
}
})
.success(function(data){
$scope.ocw = data;
console.log($scope.ocw);
});}]);
But sometimes the browser show it, sometimes not - why is that ? And in IE10 it is not working - no support in ie 10 ?

Related

SyntaxError: Unexpected token U in JSON at position 0 when i make post request

I am making a post request to an api with submit() function which is attached to a ng-click directive sending the data in JSON format, it returns this error.
It is running fine on postman so the error is on client side only.
Also the email and selectedIds variables are not empty.
Here is my controller file:
app.controller('categoryController', ['$scope', '$rootScope', '$sce', '$http', '$timeout','$window', function($scope, $rootScope, $sce, $http, $timeout, $window) {
$scope.allCategories = {};
$http({
method: 'GET',
url: 'http://qubuk.com:8081/api/v1/alltag'
})
.then(function (data) {
// console.log("DATA:" + JSON.stringify(data.data.categories[0].displayName));
// console.log("DATA category:" + JSON.stringify(data.data.categories));
$scope.allCategories = data.data.categories;
});
$scope.selectedIds = [];
$scope.change = function(category, active){
if(active){
$scope.selectedIds.push(category.id);
}else{
$scope.selectedIds.splice($scope.selectedIds.indexOf(category.id), 1);
}
// console.log("SELECTED IDS:" + $scope.selectedIds);
};
$scope.email = "faiz.krm#gmail.com"
console.log("email is "+ $scope.email);
$scope.submit = function () {
var tagsData = {"emailId": $scope.email,
"tagsId": $scope.selectedIds};
console.log("tagsData:" + JSON.stringify(tagsData));
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: tagsData
})
.then(function (data) {
console.log("Ids sent successfully!");
alert("successful");
$window.location.href = '/app/#/feed';
})
};
// console.log("amm Categories:" + JSON.stringify($scope.allCategories));
}]);
edit: the response is not a JSON object... it is a string. I do think error is due to this only... how can i resolve it on the front end...
Try to add:
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
to your request:
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: tagsData,
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
})
Alternately try to pass a stringify data:
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: JSON.stringify(tagsData),
headers: {'Content-Type': 'application/json'}
})

How do I refresh ng-repeat after an Angular Update

Using the code below, I am able to add items in my database, but the table showing the current entries doesn't update (I thought Angular did that automatically?) --- How do I force a refresh of the data?
.controller("addItemsController", function ($scope, $http) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyContacts')/items";
var vm = $scope;
var requestDigest = $("#__REQUESTDIGEST").val()
vm.addContact = function () {
return $http({
headers: { "accept": "application/json; odata=verbose", "X-RequestDigest": requestDigest, "content-Type": "application/json;odata=verbose" },
method: "POST",
url: url,
data: {
'Title': vm.LastName,
'FirstName': vm.FirstName,
"__metadata": { "type": "SP.Data.MyContactsListItem" }
}
})
.then(saveContact)
.catch(function (message) {
console.log("addContact() error: " + message);
});
function saveContact(data, status, headers, config) {
alert("Item Added Successfully");
return data.data.d;
}
}
})
NOTE: I tried using $scope.contacts.push(data) as suggested elsewhere in the forum, but contacts came back undefined (?!)

how to pass null as value of a variable in data of ajax method

I want to send a null value in the "mailID" field as email id is not a required field in the form.
var app = angular.module('MyApp', [])
app.controller('MyController', function($scope, $http, $window) {
$scope.ButtonClick = function() {
var post = $http({
method: "POST",
url: "url",
dataType: 'json',
data: {
name: $scope.Name,
mailID: $scope.MailID,
},
headers: {
"Content-Type": "application/json"
}
});
post.success(function(data, status) {
$window.alert(data.d);
});
post.error(function(data, status) {
$window.alert(data.Message);
});
}
});
When the MailID is not set, just don't send it along your data object.
Your server needs to check wheter the MailID is available or not.
var app = angular.module('MyApp', [])
app.controller('MyController', function($scope, $http, $window) {
$scope.ButtonClick = function() {
var data = {};
data.name = $scope.Name;
angular.isDefined($scope.MailID) data.MailID = $scope.MailID;
var post = $http({
method: "POST",
url: "url",
dataType: 'json',
data: data,
headers: {
"Content-Type": "application/json"
}
});
post.success(function(data, status) {
$window.alert(data.d);
});
post.error(function(data, status) {
$window.alert(data.Message);
});
}
});

Angularjs parsses non JSON POST response

I send a POST request to a server. As response the server send a http code and a plain text.
return Response.status(200).entity("Started").build();
AngularJS try to parse the response to json and I get a parsing error
Error: JSON.parse: unexpected character at line 1 column 1 of the JSON
data
This is my Angular code
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/server/start';
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
return str.join('&');
},
data: {name: $scope.name}}).then(function(html) {
//success callback code
//console.log(html)
}, function(html) {
//error callback code
//console.log(html)
});
}
You need to override transform response function
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/server/start';
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
return str.join('&');
},
transformResponse: [
function (data) {
return data;
},
],
data: {name: $scope.name}}).then(function(html) {
//success callback code
//console.log(html)
}, function(html) {
//error callback code
//console.log(html)
});
}

Converting ajax api post to $http post in angular js getting a 404

I'm trying to create a chat app where you can log into the incontact chat api (discard the weatherApp naming.. ).
This is the API documentation for the incontact chat api:
function startAgentSession() {
var startSessionPayload = {
'stationId': 'string',
'stationPhoneNumber': 'string',
'inactivityTimeout': 'integer - 30-300, or 0 for default',
'inactivityForceLogout': 'boolean',
'asAgentId': 'integer'
}
$.ajax({
//The baseURI variable is created by the result.base_server_base_uri
//which is returned when getting a token and should be used to create the URL base
'url': baseURI + 'services/{version}/agent-sessions',
'type': 'POST',
'headers': {
//Use access_token previously retrieved from inContact token service
'Authorization': 'bearer ' + accessToken,
'content-Type': 'application/json'
},
'data': JSON.stringify(startSessionPayload),
'success': function (result) {
//Process success actions
return result;
},
'error': function (XMLHttpRequest, textStatus, errorThrown) {
//Process error actions
return false;
}
});
``}
This is my attempt to convert in angular js, but for some reason I keep getting a 404, however, I'm at a loss for what I've done wrong..
weatherApp.controller('launchedController', ['$scope', '$http', '$document', function ($scope, $http, $document) {
$scope.clientResult = {};
$document.ready(function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i < vars.length; i++) {
var pair = vars[i].split("=");
query_string[pair[0]] = pair[1];
}
if (typeof(query_string.access_token) != "undefined") {
var result = {};
result.state = query_string.state;
result.scope = query_string.scope;
result.access_token = query_string.access_token;
result.expires_in = query_string.expires_in;
result.resource_server_base_uri = query_string.resource_server_base_uri;
result.token_type = query_string.token_type;
}
$scope.clientResult = result;
});
console.log($scope.clientResult);
$scope.startSessionPayload = {
'stationPhoneNumber': '55555555555',
'inactivityTimeout': '0',
'inactivityForceLogout': 'false'
};
$http({
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}).success(function(data) {
$scope.data = data;
consoloe.log('data', $scope.data)
}).error(function(status) {
$scope.status = status;
});
}]);
400 error is bad request. My guess is
replace
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}
with
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: $scope.startSessionPayload
}

Resources