Prevent loading from cache for a JSON file - javascript

When I load the page for first time, I'm getting 200 status code and the page is loading file. The problem is from second time getting 304 status and the page is not working. How to set the cache control off for the particular JSON file in my JS file
var app = angular.module("myApp", ['angular.filter']);
app.controller("deviceCtrl", function($scope, $rootScope, $http,$timeout) {
var planReq = $http.get("data/callplans.json").then(function (response1) {
$scope.callplanList = response1.data;
return response1;
});
});

try this..:
var planReq = $http.get("data/callplans.json?r=" + Math.random() ).then(function (response1) {

Related

How do I make file input optional with ng-file-upload?

I am trying to submit a form with ng-file-upload that contains additional form data. I had it working fine when the file was required, but now the client wants the file upload to be optional. I modified the PHP service to accept the new data, and it works fine.
The issue is displaying a success message when there is no file attached to the form. The data is received and processed fine by the service, but now I can't get it to indicate that the submission was successful.
I really don't want to have to shift gears at this point, and I like ng-file-upload's preview feature. I tried changing the checked variable in the ng-show directive for the success message and setting it in the .then function, but that doesn't work.
The only thing I can think of is to branch the code based on whether the file input is present and send it via regular $http if it isn't, but is there a better way?
Here's my controller code:
app.controller('adController', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
//$scope.text = "Is this working?";
$scope.ad = {};
$scope.isSaving = false; // disables fieldset to prevent accidental double-click submissions
$scope.successful_post = false;
$scope.errorClass = function(el) {
var s = $scope.adApplicationForm[el];
return (s.$invalid && s.$dirty) ? "has-error" : "";
};
$scope.submitForm = function(valid) {
console.log("Form Submitted" + valid)
return valid;
};
$scope.uploadPic = function(file) {
$scope.isSaving = true;
file.upload = Upload.upload({
url: 'php/upload_ad.php',
data: {ad: $scope.ad, file: file},
});
file.upload.then(function (response) { // success
$timeout(function () {
file.result = response.data;
});
$scope.isSaving = false;
$scope.successful_post = true;
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
};
}]);
Thanks for your help.

how to display a loading image in angular js

Hello great Stackoverflow, am learning angular js and so am querying database records via angular js and everything works fine. now i want to display a loading image as the database content is loading and the image will fade off as soon as the content is loaded. please how do i achieve that. Thanks
below is the working code
var app = angular.module('angularTable', ['angularUtils.directives.dirPagination']);
app.controller('listdata',function($scope, $http){
$scope.users = []; //declare an empty array
$http.get("data.php").success(function(response){
$scope.users = response; //ajax request to fetch data into $scope.data
});
$scope.sort = function(keyname){
$scope.sortKey = keyname; //set the sortKey to the param passed
$scope.reverse = !$scope.reverse; //if true make it false and vice versa
}
});
You can add smth like $scope.loading = true; before $http.get("data.php").success(function(response){ line.
And $scope.loading = false; inside success function.
In markup, smth like <table ng-hide="loading"> and <img ng-show="loading" src="loader.gif">

ngCordova FileTransfer returning http_status: null when downloading file from FTP

I am trying to download a file from a FTP server using Cordova. I have ngCordova and the Filetransfer plugins installed. Below is my code:
angular.module('TestApp', ['ionic', 'TestApp.controllers', 'charts.ng.justgage', 'pascalprecht.translate', 'ngCookies', 'ngCordova'])
var app = angular.module('TestApp.controllers', [])
app.controller('FileDownloadCtrl', function($scope, $timeout, $cordovaFileTransfer) {
$scope.downloadFile = function() {
var url = "ftp://URL/somefile.xml";
var filename = url.split("/").pop();
alert(filename);
var targetPath = cordova.file.externalRootDirectory + filename;
var trustHosts = true;
var options = new Object();
var headers = { 'Authorization': 'Basic Login_cred' };
options.headers = headers;
alert(cordova.file.externalRootDirectory);
alert(options.headers);
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(result) {
// Success!
alert(JSON.stringify(result));
}, function(error) {
// Error
alert(JSON.stringify(error));
}, function (progress) {
$timeout(function () {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
})
});
}
});
Angular.module is located in a different JS file in the actual code
This code returns the following alerts:
somefile.xml
file://storage/emulated/0/
[object Object]
{"code":2,"source":ftp://URL/somefile.xml","target":file:///storage/emulated/0/somefile.xml","http_status": null,"body":null,"exception":null}
I have tried downloading a file from a website hosted on the ftp (http://website/somefile.xml), which worked just fine. I am pretty sure I am doing something wrong with the header. I have also tried to put the Login_creds into the target url like this: ftp://username:password#URL/somefile.xml, this did not work but it could be browser specific.
ngCordova File Transfer does not work with ftp:// URL's, when I switched to a password protected http solution it worked.

i need to parse json file in 10 files interval

i am getting json data from a files and create another json files in each loop and send request for that json files here is my code for creating json files
var derivatedFeatures = ["RMS","sb2xMagnitudev_ipspeak", "sbSubsynchronousv_ipspeak", "PeakPeak_mil", "sbHighFrequency_grms", "TruePeak_ips", "PeakPeak_g", "sb1xMagnitudev_ipspeak","Crestfactor"];
$.each(derivatedFeatures,function(index,feature){
$.each(data,function(index,item){
var featurefile ="Lines_"+feature+'_'+item['Line']+'_'+item['Component'].split(" ").join("_")+'.json'
filedata = {
file:featurefile,
site:item['Site'],
area:item['Area'],
line:item['Line'],
equipment:item['Equipment'],
component:item['Component'],
feature:feature
};
frank.sendAjax('/static/data/json/'+featurefile,'', 'GET', anomaliesDataAppend,filedata);
});
});
i want to load 10 files first
after page scroll i want to load 10 more
and processes continue
Reason for doing this
page stuck while loading all of json files and processing its data
i have 2000+ json files
i hope this help you:
here is i coded for your solution
$.each(derivatedFeatures,function(index,feature){
$.each(data,function(index,item){
indexnum++;
var featurefile ="Lines_"+feature+'_'+item['Line']+'_'+item['Component'].split(" ").join("_")+'.json'
filedata.push({file:featurefile,
site:item['Site'],
area:item['Area'],
line:item['Line'],
equipment:item['Equipment'],
component:item['Component'],
feature:feature,
indexnum:indexnum
});
});
});
loadFeatureFiles(filedata,0);
var loadFeatureFiles = function(filedata,indexnum){
var startfrom=indexnum;
var endto=startfrom+10;
for (var i=startfrom;i <= endto;i++) {
requestdata={filedata:filedata[i],indexnum:i};
frank.sendAjax('/static/data/json/'+filedata[i]['file'],'', 'GET', anomaliesDataAppend,requestdata);
};
};
assign data= rows and get when user scroll down and pass in the function
//data is induxnum
loadFeatureFiles(filedata,data);

AngularJS issue with getting external JSON

Okay so I am new to AngularJS, and am trying to get data from an external API. The end result of this is basically going to help me understand angularjs, using external data, some more as well as getting some stats for Call Of Duty Ghosts for my account or others that I search for.
I know that $http.jsonp is the way to go, but the API doesn't really support it as well as CORS... I have accounted for that. I have been able to use jquery to test to make sure I can do it, but am unable to figure it out with AngularJS.
One issue I am having using whateverorigin and anyorigin from https://stackoverflow.com/a/7910570/1888585 and https://stackoverflow.com/a/6104416/1888585 is that I am getting http error 500 (Internal server error)
Without them I am getting an error regarding the json I am getting (which is valid json, checked with json linter) -> 'Uncaught SyntaxError: Unexpected token : '
So here is what I have:
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-controller="GhostsCtrl">
<div id="text">
Data from site: {{getGhostData()}}
Data from site: {{info}}
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.15/angular.js"></script>
<script>
var myApp = angular.module('myApp', []);
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url="+url+"&callback=?";
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
//-----------
myApp.service('dataService', function($http) {
console.log("in service!!");
this.getData = function() {
console.log("http fn");
resp = "test";
// from here i get the syntax error
$http.jsonp("http://"+url+"&callback=JSON_CALLBACK")
.success(function(data) {
console.log("Data gotten");
console.log(data.contents.user);
resp = "Success";
}).error(function(data ) {
console.log("error");
resp = "error";
});
return resp;
}
});
myApp.controller('GhostsCtrl', function($scope, $http, dataService){
$scope.info = null;
$scope.info = dataService.getData();
$scope.getGhostData = function() {
// from here I get the 500 error
delete $http.defaults.headers.common['X-Requested-With'];
$http.jsonp(wrapURL4).success(function(data) {
console.log("success: "+data.contents);
$scope.info = data.contents.user;
}).error(function(data) {
console.log("error: " + data);
});
}
});
</script>
</body>
</html>
And for my jquery code that works just fine:
$.getJSON('http://anyorigin.com/dev/get?url=api.codcp.com/user_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=?', function(data){
$.each(data.contents.user, function(val, idx) {
$("#text span").append(val+" ");
})
console.log(data.contents.user);
});
The json that comes back is as follows:
{"user":{"profile":{"ucdid":"3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c","gamertag":"xNF6xVENGE","network":"xbl","image":"http://avatar.xboxlive.com/avatar/xNF6xVENGE/avatarpic-l.png","kdr":1.109316019930545,"winr":2.7632311977715878,"kill":14694,"deaths":13246,"wins":992,"losses":359,"hoursPlayed":147.32049180327868,"currentStreak":0,"preferredWeapon":"weapon.iw6_arx160"},"squadMember":{"gamertag":"Erskine","xp":1031872,"background":20,"patchbacking":0,"patch":"patch_590","level":57,"nextLevelXp":1070000,"nextLevel":58,"prevLevel":56,"prevLevelXp":1030000,"progress":0.0468,"prestige":6},"careerHistory":{"blackops2prestige":3,"mw3prestige":6,"nextreadblackops2":1405837382,"nextreadmw3":1405841587,"playedblackops2":true,"playedmw3":true},"accounts":["xbl","ucd"],"clan":{"teamId":34018,"name":"xATFWx","memberCount":24,"tag":"ATFW","motto":"Search & destroy ","mottoBg":22,"motd":"","stats":null,"entitlements":268435448,"cxp":1991990,"kdr":1.5,"winp":74,"chat_token":"a2236f048c2a5ab71473b6765909a7f88b8716782dff8fd7b1f9df43b4b2c00ad60ba1e1a47cbea0153f590b89b698de9b91e240a8427fae4a9d8d48ea10d4fe941ab40f62acca0497e3b9c39967621abb9d6c2863ac1935d4fc193b44e2bb19","clanLevel":25,"progress":1,"nextLevelXp":1991990,"cxpNeeded":0,"nextLevel":25,"membership":0,"invited":null}}}
If there is a way I can either call jquery from angularjs easily, or avoid either error I get would be great.
I created a fiddle to figure out what your problem may be and found out that your return statement was getting fired before parsing the data in the service. I have modified the service in order to return a callback and it will work fine.
Since I cannot mock your server request here is sample fiddle and code snippet
myApp.service('dataService', function($http) {
console.log("in service!!");
return {
getData: function(callback) {
console.log("http fn");
resp = "test";
// from here i get the syntax error
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data.found);
resp="success";
callback(resp);
});
}
}
});
Looks like there are 2 reasons the anyorigin URL is not working.
The URL parameter needs to be properly encoded.
The callback should be JSON_CALLBACK instead of ?
Try this...
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url=" + encodeURIComponent(url) +"&callback=JSON_CALLBACK";
This should build this URL which properly returns a JSONP response that can be consumed by angular:
http://anyorigin.com/get/?url=api.codcp.com%2Fuser_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=JSON_CALLBACK
See this Fiddle: Live Demo
The jQuery's $.getJSON() is not a jsonp, so if you are able to retrieve the data by $.getJSON(), you could also do it with a normal $http.get() (of course with the use of anyorigin.com).
It seems the api.codcp.com doesn't support JSONP, it response with a normal JSON regardless of a callback=? exists in a url or not.
Fix this for starters, as it is just mixing single and double quote strings in concatenation:
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
By the way watch out. He is out there to get you !
Motto:
Search & destroy
and he's armed!
If you have not figured out the jsonp callback in angularjs! here is something that helped me:
$http.jsonp("http://anywebsite.com/?json=get_recent_post&callback=JSON_CALLBACK")
I hope you find this helpful.
jv

Categories

Resources