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.
Related
When i click on Buy Now button the next page appears but it is not showing the contents which want it to show. What is wrong with this code?
This is HTML code:
<div class="card-body" style="height:260px;">
<p class="card-text"> Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible</p>
</div>
<div class="card-footer" style="height:56px;">
<center><button type="submit" id="javabtn" onclick="BuyJava()" value="Java" class="btn btn-primary">Buy Now</Button></center>
</div>
This is second page code which opens after clicking on Buy Now
<div class="container" id="containerJava">
<div>
<div>
<label style="font-size: 20; margin-top:50px; margin-left: 5px;">Course Name :-</label>
<p id="lblcourse"></p>
</div>
<div>
<label style="font-size: 20; margin-left: 5px;">Course Duration :-</label>
<p id="lblduration"></p>
</div>
<div>
<label style="font-size: 20; margin-left: 5px;">Course Price :-</label>
<p id="lblprice"></p>
</div>
And this is the JavaScript code
function BuyJava() {
document.getElementById("lblcourse").innerHTML = "Java";
document.getElementById("lblduration").innerHTML = "6 Months";
document.getElementById("lblprice").innerHTML = "6000/-";
}
As you can see below, the page shows that the values haven't been inserted:
You are using an a element which is redirecting the user to another page. The JavaScript will run on click of the button when the user is on the first page. However it will not run on the second page, as it has no way of knowing the code was supposed to be executed. If you visit BuyCourse.html directly, do you expect a code to run? No.
One way to make this work is by adding parameters to the URL of the GET call, then on the second page extract the parameters from the URL with a JavaScript code, and update the content of the page.
Below is an example of such method: in the first page we have removed the a tag. Instead we will handle the redirection with JavaScript. Instead of just redirecting to BuyCourse.html we will redirect to BuyCourse.html with some parameters. A way to do this is making a GET call and adding parameters to the URL. You can read more here about it.
For instance, here we are retrieving the value of the button that was clicked and adding it to the URL path. You can have multiple parameters of course. The URLSearchParams class will handle the conversion object -> url param object. Once stringified URLSearchParams will look just like the path you want.
function BuyJava(element) {
// here you can pass as many parameters
// as you want in a key -> value format
const params = {
value: element.value
}
// convert the param object into an URLSearchParams
// object which is a built-in structure
const searchParams = new URLSearchParams(data);
// redirect the user to the new page with the params
window.location = 'BuyCourse.html?' + searchParams
}
<div class="card-body" style="height:260px;">
<p class="card-text"> Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible</p>
</div>
<div class="card-footer" style="height:56px;">
<center><button type="submit" id="javabtn" onclick="BuyJava(this)" value="Java" class="btn btn-primary">Buy Now</button></center>
</div>
When clicking on the button, it should redirect you to something like 'BuyCourse.html?value=Java'.
On the second page you will have to retrieve the parameters... this time from the URL itself. You can get the URL of the current page with document.location then create an URL object and select the key you want:
const url = new URL(document.location);
const value = url.searchParams.get('value');
document.getElementById("lblcourse").innerHTML = value;
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.
I am very new to using APIs and am having a difficult time making a GET request to IP Geolocation API. I am not sure if the problem is with my code or with something concerning CodePen (it's probably my code).
I took the JavaScript directly from the example listed on IP Geolocation API page. I was going to modify it after seeing it work in action but I couldn't get it work at all. I tried modifying the URL to include both http:// and https://.
JavaScript:
$(document).ready(function() {
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
$.each(data, function(k, v) {
table_body += "<tr><td>" + k + "</td><td><b>" + v + "</b></td></tr>";
});
$("#GeoResults").html(table_body);
});
});
HTML:
<div class="weather">
<div class="row title">
<h1>weather</h2>
</div>
<div class="row icon">
</div>
<div id = "GeoResults" class="row temp">
<p class = "city">City here</p>
</div>
</div>
URL to my CodePen: https://codepen.io/mattr8/pen/yXEMRM
API I am trying to use: http://ip-api.com/docs/api:json
Codepen doesn't want to work with ip-api.com because of https. Because codepen is served over https it will block any requests that are not https. If you go to http://ip-api.com/json/?callback=? you will see the information you're trying to reach. If you go to https://ip-api.com/json/?callback=? you will receive an error.
The jsbin example they link to does not use https, so it works fine.
So to fix your issue, create an example on a service or your own machine using http, not https for the request.
I am facing a situation that I don't know how to proceed I will try to be clear about what I want to do: here it goes I have 2 files one called index.php (where it's almost all of it HTML code) other indexphp.php where I'm handling PHP code, connecting to DB etc.
here's a print screen of my index.php, this is supposed to be a dashboard that you access after logging in in the application (where I am nesting my HTML code)
dashboard
I am using this
if (!isset($_SESSION['nivel_user'])){
header('Location: /php/logout.php');
} else {
$tu = $_SESSION['nivel_user'];
$userid = $_SESSION['idformador'];
$username = $_SESSION['user'];
}
Session variables in both index.php and indexphp.php and I want it to show different queries according to my login (I have different types of access levels) the results of my queries are supposed to be shown in that dashboard instead of those numbers you see at the top of that print screen, right now there are static values and I want them to be dynamic according to my queries.
I tried something like this but it doesn't work. (Note: Those queries need to be updated on page load since after logging in I automatically access the dashboard)
$(document ).ready(function(){
$('#query1').load('indexphp.php'){
<div class="row tile_count">
<div class="col-md-2 col-sm-4 col-xs-6 tile_stats_count">
<span class="count_top"><i class="fa fa-user"></i> </span>
<div class="count" id="query1">2</div>
<span class="count_bottom"><i class="green">100% </i> </span>
</div>
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