Angular HTTP Empty Return - angularjs

I have a pretty basic Angular Controller:
function PirateController($scope, $http) {
$scope.DetermineBooty = function () {
$scope.Processing = true;
$scope.SavedCount = $scope.PirateCount;
$scope.PirateCount = 'Please wait for Booty...';
$http.get('http://www.Suamere.com/Apps/SCA/API/Booty/' + $scope.SavedCount).
success(function (data) {
if (data != '"0"') {
$scope.ResultText = $scope.SavedCount + ' Pirates found a minimum of ' + data + ' coins.';
$scope.PirateCount = $scope.SavedCount;
} else {
$scope.ResultText = $scope.SavedCount + ' - There is no reason to calculate with that value.';
$scope.PirateCount = "";
}
$scope.Processing = false;
}).
error(function (data) {
$scope.ResultText = $scope.SavedCount + ' - There is no reason to calculate with that value.';
$scope.PirateCount = "";
$scope.Processing = false;
});
};
}
When I publish this to my website, the Error never hits, and that's good. Also, the Success hits and process correctly every time, and that's good.
But when I'm running this on my localhost in VS2013, the error always hits. And the data is always empty.
However, in Fiddler, the result appears to be comming back correctly either on my website or on my localhost. So why, only in my VS2013, is Angular catching empty when the HTTP Return obviously has something in it.

If you are using an absolute URL as shown then when you run on localhost you are making a cross domain request.
Use relative URL's or set the domain using a variable

Related

How to pass php response data from one page to another page in angularjs without using localstorage

i have one doubt how can i pass data from one page to another page in angularjs without using localstorage and data should exist even if user reload that page.
Is there any way out from here or not?
Thank's in advance
you can use cookie's :
https://docs.angularjs.org/api/ngCookies/service/$cookies
you can refer to this JSbin link for example:
http://jsbin.com/duxaqa/2/edit
Also, there is a nice stackoverflow answer that match your needs i think, with a more complete explanation than mine:
How to access cookies in AngularJS?
You can put data to cookie
// set cookie on one page:
setCookie("key", value);
// get cookie on another page:
var val = getCookie("key");
Using functions:
function setCookie(name, value, options) {
options = options || {};
var expires = options.expires;
if (typeof expires == "number" && expires) {
var d = new Date();
d.setTime(d.getTime() + expires * 1000);
expires = options.expires = d;
}
if (expires && expires.toUTCString) {
options.expires = expires.toUTCString();
}
value = encodeURIComponent(value);
var updatedCookie = name + "=" + value;
for (var propName in options) {
updatedCookie += "; " + propName;
var propValue = options[propName];
if (propValue !== true) {
updatedCookie += "=" + propValue;
}
}
document.cookie = updatedCookie;
}
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
But keep in mind that cookies size limited: 4093 bytes per domain.
you can pass data to another page using $rootScope or $cookieStore. But, only $cookieStore will save data when user reload the page. Take a look how to implement example:
angular.module('cookieStoreExample')
.controller('ExampleController', function($cookieStore) {
// Put cookie
$cookieStore.put('myFavorite','oatmeal');
// Get cookie
var favoriteCookie = $cookieStore.get('myFavorite');
// Removing a cookie
$cookieStore.remove('myFavorite');
});

AngularJS ng-repeat view not updating after data update

have a some data one my page that is in a ng-repeat.
When the page and data 1st loads the data shows up.
When I move away from the page (using Angular Routing) make a change to the data (gets saved in db) then come back into the page (make call to db get new data) the ng-repeat data does not refresh. I can see the new data loading into the array and it is the new data.
I start the process on the page with
var sp = this;
sp.viewData = [];
sp.employee = [];
sp.ViewDataTwo = [];
$(document).ready(function () {
var testHeader = setInterval(function () { myTimer() }, 1000);
function myTimer() {
if (addHeaderToken() != undefined) {
clearInterval(testHeader);
sp.usageText = "";
if (sessionStorage.getItem(tokenKey) != null) {
sp.associatedInfo = JSON.parse(getassociatedInfo());
loadDataOne();
loadDataTwo();
}
}
}
});
I do this because I need to get my security toke from a JS script that I have no power over changes. So I need to make sure the code has ran to get me the token.
here are the functions I call..
function loadPasses() {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
$http.get('/api/Employee/xxx', { params: { employeeId: sp.employeeId } }).then(function (data) {
sp.viewData = data.data;
for (var i = 0; i < $scope. viewData.length; i++) {
sp.passes[i].sortDateDisplay = (data.data.status == "Active" ? data.data.DateStart + "-" + data.data[i].DateEnd : data.data[i].visitDate);
sp.passes[i].sortDate = (data.data[i].status == "Active" ? data.data[i].DateStart: data.data[i].visitDate);
}
});
}
function loadDataTwo () {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
if (sessionStorage.getItem(tokenKey) != null) $http.get('/api/Employee',
{
params: { employeeId: sp.employeeId }
}).then(function (data) {
sp.employee = data.data;
var tempPassString = "";
sp.ViewDataTwo = [];
var totalA = 0;
var totalU = 0;
for (var p = 0; p < sp.employee.dataX.length; p++) {
sp.ViewDataTwo.push(sp.employee.dataX[p].description + "(" + /** math to update description **// + ")");
totalA += parseInt(parseInt(sp.employee.dataX[p].Anumber));
totalU += parseInt(sp.employee.dataX[p].Bnumber));
}
sp.usageArr.push(" Total: " + totalA- totalU) + "/" + totalA + " Available");
//$scope.$apply();
});
}
One my view sp.viewData and sp.ViewDataTwo are both in ng-repeats.
Works well on load.. when I go out and come back in. I see the data reloading. But the view does not.
I have hacked the Dom to get it to work for now. But I would like to do it the right way..
Any help.
I have used
$scope.$apply();
But it tells me the digest is already in process;
the views are in a template..
Please help

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.

serialize a client-side made string to a server-side file angularJS

So i'm building a string which is actually an xml file. Since i can't save any file from client-side for security issues, i'd like to save this string in a xml file server-side.
i've read about $http method or upload plugin but it seems a bit a complicated for just sending a string to my server.
is there an easier way to do it?
For informative purpose, here is my code :
$scope.addBlock = function(){
if($scope.parentblock == null)//creation of a lvl1 element
{
var div = document.createElement("div");
//xml creation
var elmt = document.createElement($scope.selectedtype.tagname);
//
div.setAttribute('id',$scope.blocktitle);
div.setAttribute('lvl',0);
var path = '/'+$scope.selectedtype.tagname;
div.setAttribute('path',path);
div.innerHTML = '<h1>' + $scope.blocktitle + '</h1><p> path : '+ path + '</p>';
if($scope.blockvalue)
{
div.innerHTML = div.innerHTML + '<p>' + $scope.blockvalue + '</p>';
//adding value to xml tag
elmt.innerHTML = $scope.blockvalue;
//
}
document.getElementById('blocks').appendChild(div);
//xml adding
doc.appendChild(elmt);
console.log(doc);
//
$scope.blocks.push([$scope.blocktitle,$scope.selectedtype.tagname,$scope.parentblock,path]);
}
else //creation of a lvl n element
{
var div = document.createElement("div");
//xml creation
var elmt = document.createElement($scope.selectedtype.tagname);
//
div.setAttribute('id',$scope.blocktitle);
var lvl = Number(document.getElementById($scope.parentblock[0]).getAttribute('lvl'))+1;
div.setAttribute('lvl',lvl);
var path = ($scope.parentblock[3]+'/'+$scope.selectedtype.tagname);
div.innerHTML = '<h2>' + (new Array(lvl + 1).join("&nbsp")) + $scope.blocktitle +
'</h2><p>' + (new Array(lvl + 5).join("&nbsp")) + ' path : '+ path + '</p>';
if($scope.blockvalue)
{
div.innerHTML = div.innerHTML + '<p>' + (new Array(lvl + 5).join("&nbsp")) +
$scope.blockvalue + '</p>';
//adding value to xml tag
elmt.innerHTML = $scope.blockvalue;
//
}
document.getElementById($scope.parentblock[0]).appendChild(div);
//xml adding
doc.getElementsByTagName($scope.parentblock[1].toLowerCase())[0].appendChild(elmt);
//
$scope.blocks.push([$scope.blocktitle,$scope.selectedtype.tagname,$scope.parentblock,path]);
}
//console.log(doc);
}
I need to send doc to my server.
EDIT :
i really need to send an xml since is a iso19110-normalized file that i have to save.
I tried this :
$http({
method: 'POST',
url: 'save.php',
data: { 'doc' : doc.outerHTML },
headers: {'Content-Type': 'text/xml'}
})
.success(function(data){
alert(data);
})
.error(function(){
alert('fail');
});
and this in php :
file_put_contents('test.xml', $_POST['doc'])
but i've got "index doc undefined" ...
I also tried
$http.post('save.php',doc).success(function() {
return console.log('uploaded');
});
but i got 'Converting circular structure to JSON'
So i think my problem come from the location of the data. I can't figure where it is...
If you need to send a lump of text to your server (over http) then you should use the $http.post() method. Its easy to use and works like a charm. You can receive and save the data on the server in any number of ways, presumably you have this bit worked out?
The real issue from your question, imo, is whether you really need to be sending xml? A much easier way of sending your data would be to use JSON. Then you don't need to go through all that document building rigmarole. Instead you can just build a javascript object and send it using the $http.post() method letting angular do all the work for you.
var doc;
doc = {
id: $scope.blocktitle,
lvl: 0
// rest of your doc structure here
};
$http.post('/my-url/upload/doc', doc).success(function() {
return console.log('uploaded');
});

node.js loop through array to write files

I've been working through a few others, also this of looping through array to http.get data from a variety of sources. I understand that nodeJS is working asynchronously which is allowing the files to be written empty or with incomplete data, but I can't seem to get past this point.
Problem: calls are made, files are built but the files are always empty
Goal: loop through an array to create files locally from the sites data. Here is what I've got so far:
var file_url = 'http://js.arcgis.com/3.8amd/js/esri/',
DOWNLOAD_DIR = './esri/',
esriAMD = [ '_coremap.js', 'arcgis/csv.js'];
function readFile(callback) {
if (esriAMD.length > 0) {
var setFile = esriAMD.shift(),
file_name = url.parse(file_url).pathname.split('/').pop(),
trial = setFile.split('/').pop(),
file = fs.createWriteStream(DOWNLOAD_DIR + trial);
http.get(file_url + esriAMD, function(res) {
res.on('data', function(data) {
file.write(data);
console.log(setFile + ' has been written successfully');
});
res.on('end', function(){
console.log(setFile + ' written, moving on');
console.log(esriAMD.length);
readFile(callback);
});
//readFile(callback);
});
} else {
callback();
}
}
readFile(function() {
console.log("reading finishes");
});
Any insight would really help.
thanks,
var esriAMD = [....];
...
function readFile(callback) {
...
http.get(file_url + esriAMD, function(res) {
...
concatenating strings with arrays may yield unexpected results.
you want to make sure that
you know what URLs your program is accessing
your program deals with error situations (where the fsck is res.on('error', ...)?)
Solution: I was passing the wrong variable into the http.get
Working code:
var file_url = 'http://.....',
DOWNLOAD_DIR = './location/';
esriAMD = ['one', 'two', 'three'..0;
function readFile(callback) {
if(esriAMD.length > 0) {
var setFile = esriAMD.shift(),
file_name = url.parse(setFile).pathname.split('/').pop(),
trial = setFile.split('/').pop(),
file = fs.createWriteStream(DOWNLOAD_DIR + trial);
http.get(file_url + setFile, function(res){
res.on('error', function(err){
console.log(err);
});
res.on('data', function(data){
file.write(data);
console.log(setFile + ' started');
});
res.on('end', function(){
console.log(setFile + ' completed, moving on');
});
});
} else {
callback();
}
}

Resources