AngularJS $http response misses some content - javascript

I'm trying to get the content of a website using Angular's $http service. Apparently the request is successful because console.log(response.data) prints most of the content but omits some of it. This is my code:
$http = angular.element(document.body).injector().get('$http');
function getAccess(url, token){$http({
method: 'GET',
url: url,
headers:{"Authorization": 'Bearer '+ token } })
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.log(error);
})
};
This is the first part of the omitted html:
<div class="container">
::before
<!-- ngView: -->
<div data-ng-view="" class="ng-scope">
<div id="toast-container" ng-class="config.position" class="ng-
scope toast-top-right">
<!-- ngRepeat: toaster in toasters --></div>
<div ng-controller="ConsultaTransferenciaController" class="ng-
scope">
<h3>Transferencias recibidas - (Mis compras).
<a href="" ng-click="infoayuda()"><span style="color:green"
class="glyphicon glyphicon-info-sign" aria-hidden="true">
</span> </a>
</h3>
and goes beyond..
I also tried with Fetch and it gave me the same response. Any idea why this is not included in the response? Thanks in advance.

you are trying to retrive data from a site with a simple get request. If the site is in plain html that works. But the site you are trying scrape is a single page angular application, which is a dynamic site with javascript. so this approch wont work. you can use panthomjs
or puppeteer in server side to achieve what you seek.

Related

How to create dynamic share popup

I have some post which are fetch by php while loop & each of the post has a link of share this post for e.g
Post 1 - share this post
Post 2 - share this post
Post 3 - share this post
there are many more post
I read out an jquery article and i got this->
jquery part
$('body').on('click','.js_share',function(){
var post=$(this).parents('.post');
var id=post.attr('data-id');
confirm(__['Share Post'],__['Are you sure you want to share this post?'],function(){
$.post(api['posts/reaction'],{'do':'share','id':id},function(response){if(response.callback){eval(response.callback);}
else{modal('#modal-success',{title:__['Success'],message:__['This has been shared to your Timeline']});}}).fail(function(){modal('#modal-message',{title:__['Error'],message:__['There is some thing went worng!']});});});});
html Part
<script id="modal-success" type="text/template">
<div class="modal-body text-center">
<div class="big-icon success">
<i class="fa fa-thumbs-o-up fa-3x"></i>
</div>
<h4>{{title}}</h4>
<p class="mt20">{{message}}</p>
</div>
</script>
The above script doesn't work in console it shows nothing
I have added the reference __ by
<script type="text/javascript">var __=[];__["Follow"]='Follow';__["Share Post"]='Share Post';__["Remove"]='Remove';__["Error"]='Error';__["Success"]='Success';__["Loading"]='Loading';__["Like"]='Like';__["Unlike"]='Unlike';__["Delete Comment"]='Delete Comment';__["There is some thing went worng!"]='There is some thing went worng!';__["This has been shared to your Timeline"]='This has been shared to your Timeline';</script>

JSON data not showing up when I change http.jsonp() URL

I'm trying to read data from an external JSON file using AngularJS.
Here is my HTML
<div class="panel panel-default" ng-controller="MyAppController">
<div class="panel-heading">
<div class="input-group">
<input ng-model="query" type="text" placeholder="What file are you looking for?" class="form-control"><span ng-click="clearFilter()" ng-disabled="query.length == 0" class="input-group-addon"><i class="glyphicon glyphicon-remove"></i></span>
</div>
</div>
<div class="panel list-group">
<span data-ng-repeat="cat in cats | filter: query" class="list-group-item animate-repeat">{{cat.title}}
</span>
<div class="clearfix"></div>
</div>
</div>
It works fine when I use this in my JS file and data shows up in a list.
function MyAppController($scope, $http) {
var url = 'http://jobs.github.com/positions.json?callback=JSON_CALLBACK';
$http.jsonp(url).success(function(data) {
$scope.cats = data;
});
}
But when I change the URL to my personal site nothing shows up even though I literally just copied and pasted everything in the github JSON file to a local JSON file. (just to test it out)
function MyAppController($scope, $http) {
var url = 'http://ciagent.com/Website-files/positions.json?callback=JSON_CALLBACK';
$http.jsonp(url).success(function(data) {
$scope.cats = data;
});
}
http://ciagent.com/Website-files/positions.json?callback=JSON_CALLBACK &
http://jobs.github.com/positions.json?callback=JSON_CALLBACK have the same exact content but only the github one works with my angular app for some reason.
Any reasons as to why it's doing this?
Assuming you are using a static resource file you need to realize that the string 'JSON_CALLBACK' is a placeholder and gets modified within each $http.jsonp() request to something else.
You should be able to see this in the actual request URL in network tab of browser dev tools.
You can also open the github version in browser and change the value to see that it is not static on their server and will adjust to whatever value is sent.
If you want to use jsonp server side it needs to return dynamic value of the callback GET parameter value.
+1 to what #charlietfl said. Also, be sure to set Content-Type:application/javascript;charset=utf-8 in your response headers.

Angular dynamically include html

I want to include HMTL for Bootstrap modal on click but I cannot get it to work.
In my controller I have this code:
$scope.onFollowingClick = function () {
console.log('clicked');
$scope.isFollowingModal = true;
$('#FollowingModal').modal('toggle');
};
And my HTML looks like this:
<div ng-if="isFollowingModal">
<div class="modal modal-alternate fade" ng-include="'/Templates/Modals/Public/ModalFollowing.html'" id="FollowingModal"> </div>
</div>
And when I click button nothing happens ("clicked" is logged in console), in browser when I inspect element, I only see:
<!-- ngIf: isFollowingModal -->
And no network request to fetch ModalFollowing.html is logged.
What am I doing wrong ?
If we go this way, using $http service is really helpful even though ngInclude fetches, compiles and includes an external HTML fragment.
$scope.onButtonClick = function() {
$http
.get('/Templates/Modals/Public/ModalFollowing.html')
.success(function(response) {
$('modal')
.html(response)
.modal('show');
});
}
And never forget about async :P

Display alert message after page reload

I have to call $route.reload(); in controller 2 addData API call so that I can get the added data in my UI. But then the text 'Data added successfully' goes away due to page refresh.
controller 1:
$rootScope.$on('reloaded', function(event, data) {
$scope.$parent.alerts.length=0;
$scope.$parent.alerts.push({type: 'success',msg: 'Data added successfully'});
});
controller 2:
$scope.add = function() {
someAPIService.addData(JSON.stringify($scope.rows)).success(function(response) {
ngDialog.close('ngdialog1');
$route.reload();
$rootScope.$emit('reloaded', "true");
});
}
HTML Part:
<section>
<div ng-controller="controller3">
<alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert>
</div>
<div class="row form-inline" ng-controller="controller2 as vm">
<!-- Table data with text fields-->
</div>
<script type="text/ng-template" id="addDataDialog">
<div id="frm" ng-controller="controller1" class="col-xm-6">
<div class="form-group">
<!-- Labels with text fields-->
</div>
<button class="ngdialog-button" ng-click="add()">Save</button>
</div>
</script>
</section>
NOTE: Both controllers are in the same JS file and they are used for the same HTML file.
As you want to only load the latest record list which is on server side. Then there is not need to use $route.reload(); after making post call. You need to only make ajax call to get the latest records list that will solve your problem. For making ajax you need to refer $http
$route.reload() is getting used only when you need to load
controller again with specified template in your $routeProvider when
condition
just a simple hint of an answer:
add a (specific) cookie (with javascript) before calling reload (use e.g Cookies lib),
read it on reload,
and then delete it
Also you may use local storage if it is available instead of a cookie using same steps:
add a specific entry in local storage, before calling reload
read it on reload
and then delete it
Another option to maintain state client-side is to use url parameters but these will not do for page reload

jQuery $.ajax response empty, but only in Chrome

I've exhausted every avenue of research to solve this one so hopefully someone else will think of something I just didn't.
Relatively straight forward setup, I have a html page with some javascript that makes an ajax request to a URL (in the same domain) the java web app in the background does its stuff and returns a partial html page (no html, head or body tags, just the content) which should be inserted at a particular point in the page.
All sounds pretty easy and the code I have works in IE, Firefox and Safari, but not in Chrome. In Chrome the target element just ends up empty and if I look at the resource request in Chromes developer tools the response content is also empty.
All very confusing, I've tried a myriad of things to solve it and I'm just out of ideas. Any help would be greatly appreciated.
var container = $('#container');
$.ajax({
type: 'GET',
url: '/path/to/local/url',
data: data('parameters=value&another=value2'),
dataType: 'html',
cache: false,
beforeSend: requestBefore,
complete: requestComplete,
success: requestSuccess,
error: requestError
});
function data(parameters) {
var dictionary = {};
var pairs = parameters.split('&');
for (var i = 0; i < pairs.length; i++) {
var keyValuePair = pairs[i].split('=');
dictionary[keyValuePair[0]] = keyValuePair[1];
}
return dictionary;
}
function requestBefore() {
container.find('.message.error').hide();
container.prepend('<div class="modal"><div class="indicator">Loading...</div></div>');
}
function requestComplete() {
container.find('.modal').remove();
}
function requestSuccess(response) {
container.empty();
container.html(response);
}
function requestError(response) {
if (response.status == 200 && response.responseText == 'OK') {
requestSuccess(response);
} else {
container.find('.message.error').fadeIn('slow');
}
}
All of this is executed in a $(document).ready(function() {});
Cheers,
Jim
#Oleg - Additional information requested, an example of the response that the ajax call might receive.
<p class="message error hidden">An unknown error occured while trying to
retrieve data, please try again shortly.</p>
<div class="timeline">
<a class="icon shuttle-previous"
rel="max_id=16470650733&page=1&q=something">Newer Data</a>
<a class="icon shuttle-next"
rel="max_id=16470650733&page=3&q=something">Older Data</a>
</div>
<ol class="social">
<li class="even">
<div class="avatar">
<img src="sphere_normal.gif"/>
</div>
<p>
Some Content<br/>
<span class="published">Jun 18, 2010 11:29:05 AM</span> - <a
target="_blank" href="">Direct Link</a>
</p>
</li>
<li class="odd">
<div class="avatar">
<img src="sphere_normal.gif"/>
</div>
<p>
Some Content<br/>
<span class="published">Jun 18, 2010 11:29:05 AM</span> - <a
target="_blank" href="">Direct Link</a>
</p>
</li>
</ol>
<div class="timeline">
<a class="icon shuttle-previous"
rel="max_id=16470650733&page=1&q=something">Newer Data</a>
<a class="icon shuttle-next"
rel="max_id=16470650733&page=3&q=something">Older Data</a>
</div>
I just resolved a similar problem, and thought I'd post my solution in case it's of use for anyone else.
Only Firefox and Chrome were showing an empty ajax response, so it seemed to be a cross domain problem, yet everything was on the same domain.
It turned out that the 'www.', which I had superfluously and stupidly hard-coded into my ajax url was to blame. Had I been using a relative path, everything would've been fine.
I had my test site open at that particular moment as "http://domain.com", with no 'www.', so Firefox and Chrome treated it as a different domain. Navigating to "http://www.domain.com" resulted in the ajax call working in all browers.
So, given that you wrote:
url: '/path/to/local/url'
..as is the convention when we don't want to disclose our paths, I couldn't help but wonder if in fact you had written an absolute path, just as I had...?
Chrome stepped onto its own foot with local files security, so no AJAXing local files with relative paths:
http://code.google.com/p/chromium/issues/detail?id=47416
I took your source code and set up a quick test scenario but fail to replicate your problem. It is working for me just fine in both Firefox (3.6.3) and Chrome (5.0.375.70). I tried it both locally and on a remote server.
So your code is most likely not to blame. But I would also think that it's not generally a Chrome related issue.
Other people seem to have come across this though. Changing the content type had no effect in my test scenario though. It even works when I set the Content-Type to image/jpeg.
On the JQuery forums someone indicated differing behavior depending on whether he runs his application locally or on a remote server. If this was the case for you, you could compare HTTP request and response headers to track down the issue.

Categories