Unexpected token T in JSON at position 0 - angularjs

I am getting this error in console when i click submit button though my data is getting saved to backend as i wanted.
SyntaxError: Unexpected token T in JSON at position 0
at JSON.parse (<anonymous>)
at dc (angular.min.js:91)
at angular.min.js:92
at q (angular.min.js:7)
at gd (angular.min.js:92)
at f (angular.min.js:94)
at angular.min.js:131
at m.$digest (angular.min.js:142)
at m.$apply (angular.min.js:146)
at l (angular.min.js:97)
Here is my frontend code in angular
$scope.nextStep = function() {
if ($scope.selection === 'Information'){
$scope.branch.organisation = $scope.branch.organisation.id;
$scope.fact.incrementStep($scope);
}
else if ($scope.selection === 'Validation'){
var authdata = base64.encode($rootScope.globals.currentUser.user.phone + ':' + $scope.password.password);
if (authdata === $rootScope.globals.currentUser.authdata){
$scope.passwordMatch = true;
var branchArr = [];
var dynamicBranches = $scope.dynamicBranches;
for (var i = 0; i < dynamicBranches.length; i++) {
branchArr.push(dynamicBranches[i].name);
}
var params = [{
"region" : $scope.branch.region,
"branches" : branchArr
}];
Restangular.one('organisation', $scope.branch.organisation).all('add_region_and_branch_data').post(params).then(function(response) {
$scope.createdBranch = response;
$scope.fact.incrementStep($scope);
}, function(error){
///console.log('Error with status', error.statusText, 'code', error.status);
//SweetAlert.swal('Error', 'The agent couldn\'t be created. \n' + error.data.error, 'error');
console.log(error);
});
}else{
$scope.passwordMatch = false;
}
}
};
Again, my data is getting saved to api but I am getting this error. How can i fix this?

Check your HTTP-response body. AngularJS gets something what it can't parse like JSON. May be any warning or error happened and added to your API-response? I thing a problem is not in your nextStep function.
Unexpected token T in JSON at position 0 problem can happen, for example, with this HTTP-responses:
Too many params warning{"here": "is valid JSON"}
Or just warning
Too many params warning

Related

Returned gameScore Parse.Object object from Parse.Query.get documentation gives undefined gameScore object

Directly from Parse.com javascript guide:
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
success: function(gameScore) {
// The object was retrieved successfully.
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
var score = gameScore.get("score");
var playerName = gameScore.get("playerName");
var cheatMode = gameScore.get("cheatMode");
Basically gives Uncaught ReferenceError: gameScore is not defined...
Here is my code to troubleshoot this:
// Retrieve class
var GameScore = Parse.Object.extend("GameScore"); //redefine the GameScore class based on the cloud.
var query = new Parse.Query(GameScore);
var my_object;
var some_object = query.get("SQV1DZXv5p", {
success: function(gameScore) { //gameScore is the retrieved object.
alert('Object retrieved, with object ID: ' + gameScore.id);
//document.getElementById('division1').innerHTML = gameScore.id;
my_object = gameScore.id;
},
error: function(object, error) {
alert('Retrieval FAILURE, error: ' + error.message + '; Object retrieved instead is: ' + object); //object will be NULL if not found.
}
});
var score = gameScore;
document.getElementById('division1').innerHTML = my_object;
So this still throws the reference error for gameScore.
Also, the document.getELementById statement does not print the gameScore.id in my division1 div. It remains empty. But when I check to see what my_object is in the javascript console, it returns the gameScore.id correctly.
What's interesting is if I run the document.getELementById line inside the success function, then it will display the gameScore.id...
Do this:
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
success: function(gameScore) {
// The object was retrieved successfully.
var score = gameScore.get("score");
var playerName = gameScore.get("playerName");
var cheatMode = gameScore.get("cheatMode");
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
gameScore is only be available in the scope of the success block, hence the Uncaught ReferenceError. The world outside the success block does not know it exists. Do your stuff in there.
Also, .get() makes a request from the server, so it would take time to complete. Performing operations gameScore after the .get() method will result in accessing that object when it has not been fetched yet, hence another error. See #danh's comment below. For network calls like this, always perform actions on the fetched object inside the completion block.

capturing full URL of a GET request in AngularJS including query params

I'm using http interceptor. I do see all the values when I make a Restangular GET request. Here is the code for my request interceptor.
request: function (config) {
// see link below to see value of config
console.log('config', config);
// below returns full url except query string
console.log('location', $location.absUrl());
// $rootScope.cacheData is $cacheFactory
console.log('$rootScope', $rootScope.cacheData);
// only returns {id: "http", size: 3}
console.log('cache info', $rootScope.cacheData.info());
// below returns undefined
console.log('cache get', $rootScope.cacheData.get('http'));
// other codes removed since it's not related
// ........
// ........
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
config value : http://i.imgur.com/l0IsXbJ.png
Unfortunately, preparing the params captured manually is not 100% guaranteed that it will match what has been cached. I noticed that cacheFactory checks the exact string that was requested. So if our GET request's query parameters are age=12&name=scott then on our http interceptor, we prepare it the other way by putting name first then age(name=scott&age=12), cacheFactory won't find it.
So I'm trying to look for an angular service or factory that will return the full URL equal to the request we made. I tried $location but it's not giving the full GET request.
I just decided to parse the config and build it from scratch. It's working great :)
if ( config.method == 'GET' && (config.url.indexOf('v1/repeters') != -1) ) {
// Prepare the full path
var cachedUrlsLocalStorage;
var absolutePath = '';
_(config.params).keys().sort().each( function(key, index) {
var value = config.params[key];
absolutePath = absolutePath + key + '=' + value + (index < _(config.params).keys().value().length - 1 ? '&' : '');
});
cachedUrlsLocalStorage = JSON.parse(window.localStorage.getItem('cachedUrls'));
if (cachedUrlsLocalStorage) {
var exists = _.findIndex(cachedUrlsLocalStorage, function(cachedData) {
return cachedData.url == config.url + '?' + absolutePath;
});
if (!exists) {
cachedUrlsLocalStorage.push({url : config.url + '?' + absolutePath, timeExecuted : moment(), expiryTime : moment().add(10, 'minutes')});
window.localStorage.setItem('cachedUrls', JSON.stringify( cachedUrlsLocalStorage ));
}
} else {
cachedUrlsLocalStorage = [];
cachedUrlsLocalStorage.push({url : config.url + '?' + absolutePath, timeExecuted : moment(), expiryTime : moment().add(10, 'minutes')});
window.localStorage.setItem('cachedUrls', JSON.stringify( cachedUrlsLocalStorage ));
}
}

Invalid Parse.com request

I have been using parse for a while now and I am quite confused by the issue I am having.
Here is one function that I call first:
$scope.followUser = function(usernameToFollow)
{
console.log('ready to follow user: ' + usernameToFollow);
var user = Parse.User.current();
if (user)
{
var FollowUser = Parse.Object.extend('User');
var query = new Parse.Query(FollowUser);
query.equalTo('username', usernameToFollow);
query.find({
success: function(results)
{
var relationToUserPosts = user.relation('followUser');
$scope.userToAdd = results[0];//This is the user I want to add relational data to
relationToUserPosts.add(results[0]);
user.save();
},
error: function(error)
{
alert('Error: ' + error.code + '' + error.message);
}
});
}
else
{
console.log('Need to login a user');
// show the signup or login page
}
};
Next after I call that function I call this function:
$scope.addToFollowers = function()
{
var currUser = Parse.User.current();
console.log($scope.userToAdd);
var followerUser = $scope.userToAdd.relation('followers');
followerUser.add(currUser);
$scope.userToAdd.save();
};
I know for sure the $scope.userToAdd is the user I want, I know the relation I pull from the object is valid its when I try to save this object with $scope.userToAdd.save() is when I get the bad request, with no further information as to why its a bad request. Thank you in advance.
UPDATE:
The first method call has no errors and no bad requests.
Error message:
Well turns out you cannot save a user object unless your are logged in as that user time to find another solution thank you for the help eth3lbert.

Restangular TypeError: Cannot set property 'route' of null

This is a Angular function that previously worked...
$scope.InsertLabelText = function () {
var MapText = $("#txtMapLabel").val();
Restangular.setBaseUrl(BaseURL);
if (MapText != null) {
//Call WebAPI to enter text then refresh map.
var TextObjs = Restangular.all('PostObjects');
NewTextObject = {TypeMapId: "5", GrowerId: $("#GrowerName").val(), CropYear: $("#CropYear").val(), NAME: MapText, SHAPE: coordinates}
TextObjs.getList(NewTextObject).then(function (data) {
$scope.Label = data;
if ($scope.Label.Success = true) {
var geojson_format = new OpenLayers.Format.GeoJSON();
var Object_style = OpenLayers.Util.extend({}, layer_style);
Object_style.fillOpacity = 0.7;
Object_style.label = MapText;
Object_style.graphicZIndex = 4999;
Text.style = Object_style;
Text.addFeatures(geojson_format.read($scope.Label.TextObject));
LabelLine.destroyFeatures();
}
else {
console.log(data);
var Error = prompt($scope.Label.TextObject);
console.log("There was an error saving");
}
$("#divMapInputText").hide();
});
}
};
It fails on the call TextObjs.getList with the error "TypeError: Cannot set property 'route' of null"
I have 3 other functions in the same controller with the same code pattern but they all work?
Here is the whole error from chrome...
TypeError: Cannot set property 'route' of null
at g (http://localhost/FarmMapsMvc4/Scripts/ThirdParty/restangular.min.js:8:8705)
at t (http://localhost/FarmMapsMvc4/Scripts/ThirdParty/restangular.min.js:8:11154)
at http://localhost/FarmMapsMvc4/Scripts/ThirdParty/restangular.min.js:8:13225
at http://localhost/FarmMapsMvc4/Scripts/ThirdParty/lodash.min.js:72:226
at y (http://localhost/FarmMapsMvc4/Scripts/ThirdParty/lodash.min.js:16:110)
at Function.Et (http://localhost/FarmMapsMvc4/Scripts/ThirdParty/lodash.min.js:72:191)
at http://localhost/FarmMapsMvc4/Scripts/ThirdParty/restangular.min.js:8:13149
at h (http://localhost/FarmMapsMvc4/Scripts/ThirdParty/angular.min.js:78:33)
at http://localhost/FarmMapsMvc4/Scripts/ThirdParty/angular.min.js:78:266
at Object.e.$eval (http://localhost/FarmMapsMvc4/Scripts/ThirdParty/angular.min.js:88:347) angular.min.js:62(anonymous function) angular.min.js:62(anonymous function) angular.min.js:52h angular.min.js:78(anonymous function) angular.min.js:78e.$eval angular.min.js:88e.$digest angular.min.js:86e.$apply angular.min.js:88e angular.min.js:95p angular.min.js:98t.onreadystatechange

Unexpected token , in Angular code after $http request

I am submitting an $http request to my server using this code below, yet all the of sudden Angular is complaining about an "Unexpected token , " somewhere.
function sendAggrRequestToServer(url) {
var deferred = $q.defer();
$http({
method: 'GET',
encoding: 'JSON',
headers: {
'Access-Control-Allow-Origin': 'true'
},
withCredentials: true,
url: url
}).success(function (data, status, headers, config) {
var retval = data;
deferred.resolve(retval);
}).error(function (data, status, headers, config) {
logErr("Error submitting aggregation request to server: " + status);
});
return deferred.promise;
}
The strange thing is that this exact URL works successfully both in the browser and in Fiddler. And the Json data is returned as expected. However, for some strange reason my javascript code is throwing this
exception:
[app] [HT Error] Unexpected token ,
Object {exception: SyntaxError, cause: undefined}
angular.js:9778
(anonymous function) angular.js:9778
logIt logger.js:55
logError logger.js:49
(anonymous function) logger.js:32
(anonymous function) config.exceptionHandler.js:26
deferred.promise.then.wrappedCallback angular.js:11322
(anonymous function) angular.js:11405
Scope.$eval angular.js:12412
Scope.$digest angular.js:12224
Scope.$apply angular.js:12516
done angular.js:8204
completeRequest angular.js:8412
xhr.onreadystatechange
And my URL is :
http://localhost:49479/api/aggr?sid=9630a8040ee6c901a4034c07894abc317272f855c757a4c60a6a&kri=[CDSStress%20A]:[USD%2010Y%20X%20-1.25],[CDSStress%20A]:[USD%2010Y%20X%201.25]&aggrFunc=SUM([CDSStress%20A]:[USD%2010Y%20X%20-1.25]),SUM([CDSStress%20A]:[USD%2010Y%20X%201.25])&dim=Counterparty
FYI: All appears to be fine in angular.js at this point in angular, and I can indeed see the response data (which is definitely valid Json data). The callback status param has a value of "200" and the statusText is 'OK':
function completeRequest(callback, status, response, headersString, statusText) {
// cancel timeout and subsequent timeout promise resolution
timeoutId && $browserDefer.cancel(timeoutId);
jsonpDone = xhr = null;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
}
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status = status === 1223 ? 204 : status;
statusText = statusText || '';
callback(status, response, headersString, statusText);
$browser.$$completeOutstandingRequest(noop);
}
};
Here is a screen image of the break point where I can inspect the "response" param:
However, as soon as it resolves the promise and returns to my calling function, angular throws the Unexpected token error.
I have been using this for days now, but today I must have introduced something to cause this. I just can't figure out what !
Your advice and guidance is greatly appreciated.
regards.
Bob
UPDATE:
I now find Angular throwing the actual exception inside $HttpProvider() on this line :
data = fromJson(data);
inside here :
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/,
CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data);
}
return data;
}],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
post: copy(CONTENT_TYPE_APPLICATION_JSON),
put: copy(CONTENT_TYPE_APPLICATION_JSON),
patch: copy(CONTENT_TYPE_APPLICATION_JSON)
},
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
};
And sendAggregationREquest() is called from here :
function buildAndSendAggregationQuery() {
// iterate list in reportsContext , pass data to to sendAggregationRequest()
var userKRIs = vm.kriUserDataSource.get();
userKRIs.load();
var group;
var kri = '';
var aggrFunc = '';
var aggrKriFuncArray;
var dimension = vm.selectedDimen;
var dimenMulti = '';
var applyScenarioAggr = false;
if (vm.kriUserDataSource.data()[0].group == '99_HSVaR') {
applyScenarioAggr = true;
}
// Call function to build the aggr function. Return value is an array.
if (applyScenarioAggr) {
aggrKriFuncArray = reportsContext.buildAggrFunc(vm.kriUserDataSource.data(), 'AVERAGE');
}
else {
aggrKriFuncArray = reportsContext.buildAggrFunc(vm.kriUserDataSource.data(), 'SUM');
}
kri = aggrKriFuncArray[0];
aggrFunc = aggrKriFuncArray[1];
for (var i = 0; i < vm.multiSelectedDimen.length; i++) {
dimenMulti += vm.multiSelectedDimen[i] + ',';
}
dimenMulti = dimenMulti.substr(0, dimenMulti.length - 1); // ' remove final ","
sendAggregationRequest(kri, aggrFunc, dimension); //dimenMulti);
}
and finally, the response data that comes back from server prior to that exception:
{"status":"SUCCESS", "messages":[], "data":[{"attributes":[{"name":"Counterparty","type":"string"},{"name":"SUM(CDSStress A:USD 10Y X -1.25)","type":"double"},{"name":"SUM(CDSStress A:USD 10Y X 1.25)","type":"double"}],"rows":[{"id":0,"values":["Goldman",0.,0.]},{"id":1,"values":["IBM",0.,0.]},{"id":2,"values":["JP Chase",0.,0.]},{"id":3,"values":["MINESCONDIDA",0.,0.]},{"id":4,"values":["Merrill",0.,0.]},{"id":5,"values":["Nokia",0.,0.]},{"id":6,"values":["Pequot",0.,0.]},{"id":7,"values":["Pimco Fund A",0.,0.]},{"id":8,"values":["Pimco Fund B",0.,0.]},{"id":9,"values":["Deutsche",0.,0.]},{"id":10,"values":["Ditech",0.,0.]},{"id":11,"values":["GM Isuzu",0.,0.]},{"id":12,"values":["GM Opel",0.,0.]},{"id":13,"values":["GMAC",0.,0.]},{"id":14,"values":["GMAC Insurance",0.,0.]},{"id":15,"values":["GSAM",0.,0.]},{"id":16,"values":["General Insurance",0.,0.]},{"id":17,"values":["Genworth",0.,0.]},{"id":18,"values":["AIG",0.,0.]},{"id":19,"values":["Andor",0.,0.]},{"id":20,"values":["BARCLAYS",92.7731197209214,-10.1717767200607]},{"id":21,"values":["BHHSH",0.,0.]},{"id":22,"values":["BHPBFIN",0.,0.]},{"id":23,"values":["BHPSTEEUR",1468.80370935,-161.395632863801]},{"id":24,"values":["BHPSUS",0.,0.]},{"id":25,"values":["BLUESCOPEFIN",0.,0.]},{"id":26,"values":["CSFB",3.35029024626419,-0.367366071961442]},{"id":27,"values":["BLOSOFL",0.,0.]},{"id":28,"values":["GRMOBND",0.,0.]}]}]}
can you make a jsfiddle ? or at least show us how you call the sendAggrRequestToServer method.
It shouldbe
var promise = sendAggrRequestToServer(url);
promise.then(function(data) {
console.log('Success we got: ' + data);
}, function(reason) {
console.log('Failed we got: ' + reason);
}, function(update) {
console.log('Strange we got: ' + update);
});
Thx

Resources