I have been developing on firefox & the code works fine but when I tried to test on Chrome it just displays the {{err_msg}} which means angular is not working.
I am using Django 1.10 server with Rest Framework for managing get requests from the Angularjs 1.5.9 code.
I tested on Firfox, Midori & Chrome. It only works on Firefox!
I edited the hosts file so that givemecoupon.com:8000 redirects to 127.0.0.1:8000 which is my Django server.
Console error:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.9/$injector/modulerr?p0=givemecouponApp&p1=…Ic%20(https%3A%2F%2Fcode.angularjs.org%2F1.5.9%2Fangular.min.js%3A21%3A332)
at angular.js:38
at angular.js:4683
at q (angular.js:325)
at g (angular.js:4644)
at eb (angular.js:4566)
at c (angular.js:1803)
at Ic (angular.js:1824)
at ue (angular.js:1709)
at angular.js:32379
at HTMLDocument.b (angular.js:3251)
my app:
'use strict';
var givemecouponApp = angular.module('givemecouponApp', []);
givemecouponApp.controller('CouponsCtrl', ['$scope', '$http', 'givemecouponService', function CouponsCtrl($scope, $http, givemecouponService) {
$scope.finderloader=true;
$scope.err_msg = 'no error';
var myDataPromise = givemecouponService.getData();
myDataPromise.then(function(result) {
if(result.data == "Not a valid course!" || result.data == "No course passed!"){
$scope.err_msg = result.data;
}else{
$scope.coupons = result.data;
}
}, function ( result ) {
if(result.status == 429){
$scope.err_msg = "Too many requests!";
}
// TODO: handle the error somehow
}).finally(function() {
// called no matter success or failure
$scope.finderloader = false;
});
}]);
//service for getting coupon codes
givemecouponApp.factory('givemecouponService', function($http) {
var getData = function() {
// Angular $http() and then() both return promises themselves
return $http({method:"GET", url:slug_json_url}).then(function(result){ // What we return here is the data that will be accessible
// to us after the promise resolves
return result;
});
};
return { getData: getData };
});
Template:
{% load static %}
<!DOCTYPE html>
<html ng-app="givemecouponApp">
<head>
<meta charset="utf-8">
<title>Course Page</title>
<script src="https://code.angularjs.org/1.5.9/angular.min.js" type="text/javascript"></script>
<script src="https://code.angularjs.org/1.5.9/angular-resource.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="{% static 'css/spinkit.css' %}">
</head>
<body ng-controller="CouponsCtrl">
<div>
{% block content %}
<h1>Course Page</h1>
{{course_slug_url}}
{% endblock content %}
{% verbatim %}
<div>Coupons:
<div>{{err_msg}}</div>
<div ng-show="finderloader" class="sk-wave">
<h3>Looking for Coupons</h3>
<div class="sk-rect sk-rect1"></div>
<div class="sk-rect sk-rect2"></div>
<div class="sk-rect sk-rect3"></div>
<div class="sk-rect sk-rect4"></div>
<div class="sk-rect sk-rect5"></div>
</div>
<h2 ng-repeat="coupon in coupons" ng-show="coupon.id==1">
{{coupon.meta_title}}
</h2>
<h2 ng-repeat="coupon in coupons" ng-show="coupon.id==1">
Original Price: {{coupon.original_price}}
</h2>
<ul ng-repeat="coupon in coupons">Code: {{coupon.code}}
<li>Discount price: {{coupon.discounted_price}}</li>
<li>Discount rate: {{coupon.discount_rate}}</li>
<li>Valid untill: {{coupon.end_time}}</li>
{{coupon.deeplink}}
</ul>
</div>
</div>
{% endverbatim %}
{% block pass_slug %}
<script type="text/javascript">
slug_json_url = "http://givemecoupon.com:8000/api/?format=json&slug={{course_slug_url}}";
</script>
{% endblock pass_slug %}
<script src="http://givemecoupon.com:8000/static/js/app.js" type="text/javascript" charset="utf-8" async defer></script>
</body>
</html>
What is the problem???
After hours of search I managed to solve the problem.
I just changed
<script src="http://givemecoupon.com:8000/static/js/app.js" type="text/javascript" charset="utf-8" async defer></script>
to:
<script src="http://givemecoupon.com:8000/static/js/app.js" type="text/javascript"></script>
it was SublimeText snippet that created the first code which caused the problem.
It looks the async is what causes the AngularJs to not work in Chrome & break the whole script!
Asynchronous execution <script async>
Don’t care when the script will be available? Asynchronous is the best of both worlds: HTML parsing may continue and the script will be executed as soon as it’s ready. I’d recommend this for scripts such as Google Analytics.
Then after fixing the Async problem I got CORS error
XMLHttpRequest cannot load http://givemecoupon.com:8000/api/?format=json&slug=arduino-sbs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.givemecoupon.com:8000' is therefore not allowed access.
Which I solved by the help of https://github.com/ottoyiu/django-cors-headers/
by adding these lines to the settings.py file:
INSTALLED_APPS = [
#django generated
#3rd party
'rest_framework',
'corsheaders', #manage Cross-side API requests
#my apps
]
MIDDLEWARE = [
#cors headers
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
#django generated
]
# CORS allow anyone to get API calls
CORS_ORIGIN_ALLOW_ALL = True
Related
I have a handlebars template and I'm trying to use it, but when I do, I get all the tags but with no text. Here's my HTML:
<script src="../static/js/main.js"></script>
<script src="https://cdn.jsdelivr.net/npm/handlebars#latest/dist/handlebars.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script id="template" type="text/x-handlebars-template">
<li class="message">
<h6>{{username}}</h6>
<p>{{message}}</p>
<p>{{date}}</p>
</li>
</script>
And in main.js:
socket.on('message', data => {
console.log('message recieved')
console.log(data.channel)
console.log(document.querySelector("#active").innerHTML)
if (data.channel === document.querySelector("#active").innerHTML) {
console.log(data.sent_by)
console.log(data.message)
console.log(data.time)
var template = Handlebars.compile(document.querySelector('#template').innerHTML);
console.log(document.querySelector('#template').innerHTML)
const context = {'username' : data.sent_by,
'message' : data.message,
'date' : data.time,};
var html = template(context);
console.log(context)
console.log(html)
document.querySelector('#view-message').innerHTML += html
}
})
All log messages are being run so the socket is receiving data and the if condition is being triggered. I've used handlebars in a previous section of the same project and it worked fine there so I'm not sure why it's not working here. Thanks!
move your script <script src="../static/js/main.js"></script> all the way to the bottom
I'm trying to get data from this website through HTTP get method. This website has basic authentication. The data is in JSON format.
This is the rest api website:
(https://shoploapi.herokuapp.com/sellers)
// Code goes here
angular.module('myapp', ['myapp.controller']);
angular.module('myapp.controller', ['myapp.service'])
.controller('testController', function($scope, testService) {
$scope.posts = {};
function GetAllPosts() {
var getPostsData = testService.getPosts();
getPostsData.then(function(post) {
$scope.posts = post.data;
}, function() {
alert('Error in getting post records');
});
}
GetAllPosts();
});
angular.module('myapp.service', [])
.service('testService', function($http) {
//get All NewsLetter
this.getPosts = function() {
return $http.get('https://shoploapi.herokuapp.com/sellers');
};
});
angular.module('myApp', ['base64'])
.config(function($httpProvider, $base64) {
var auth = $base64.encode("bhupendra7:ice123age456");
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + auth;
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-base64/2.0.5/angular-base64.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-app="myapp">
<h1>Hello Plunker!</h1>
<div ng-controller="testController">
<div>
<ul>
<li ng-repeat="post in posts">
{{post.careof}} {{post.district}} {{post.gender}} {{post.name}}
</li>
</ul>
</div>
</div>
</body>
</html>
Here's the link to my Plunker:
(https://plnkr.co/edit/7pqljm?p=preview)
Can anyone help?
There are 2 problems in your code.
1. You have a typo
In angular.module('myApp', ['base64']), change to module name to myapp
2. The way you have injected your myapp.controller to myapp module
Change it to angular.module('myapp', []); You will also need to reorder your code. Check out the Plunker I have created for you.
Even if you fix the above two problems, you will still face a CORS problem from Heroku. Depending on your server-side technology (NodeJS, Rails etc.), you will need to enable it from the server to be able to communicate with your app. You can also look in to JSONP with AngularJS
Hope this helps
This is my first AngularJS project. I followed this website to create a simple html to display a single record by calling restful services. The rest works with the url "http://localhost:8080/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009".
Here is my html:
<html ng-app="cgApp" ng-controller="CgseqCtrl">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
</head>
<body>
<div>
<hr>
<h2>{{seq.analysisId}}</h2>
<h2>{{seq.library}}</h2>
</hr>
</div>
</body>
</html>
I defined the resource in a service js
//service.js
angular.module('cgApp', ['ngResource'])
.factory('CgseqService', function ($resource) {
return $resource('http://localhost:8080/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009',
{get: {method: 'GET'}
});
});
The controller:
//controller.js
angular.module('cgApp', ['ngResource'])
.controller('CgseqCtrl', ['CgseqService', '$scope', function (CgseqService, $scope)
{
$scope.getSeq = function(response) {
CgseqService.get(function(data) {
$scope.seq = data;
});
};
}]);
When I started my http server with Node.js and typed the url in the browser, nothing is displayed. What did I do wrong?
Several errors.
You didn't load your factory code. It looks like you only loaded your controller.js (I'm assuming your factory code is in a different file since in your example you commented it as //service.js):
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
</head>
np-controller should say ng-controller:
<html ng-app="cgApp" np-controller="CgseqCtrl">
You also never called your $scope.getSeq function:
$scope.getSeq = function(response) {
CgseqService.get(function(data) {
$scope.seq = data;
});
};
You should call $scope.getSeq() somewhere to actually invoke it.
I'm trying to refresh a Jenkins build console output in my Flask web application, however I am having trouble with the jQuery/AJAX to do it.
As you can see below, i'm just trying to get this working using a refresh button. Ideally I want to refresh {{buildinfo}} on a timer.
Currently my test function/jQuery is returning the error: Uncaught TypeError: Illegal invocation.
Heres the (working) function from my app.py I was using before I started down this path:
#app.route('/buildinfo/<job_id>/<job_number>', methods=['GET', 'POST'])
def buildInfo(job_id, job_number):
try:
console_output = server.get_build_console_output(job_id, int(job_number))
return render_template("buildinfo.html", buildinfo=console_output, job_id=job_id, job_number=job_number)
except Exception as e:
return render_template("buildinfo.html", error=str(e))
Here's the test function I have been using to receive the request and send back to the client:
#app.route('/_test')
def foo():
a = request.args.get('a', None, type=str)
b = request.args.get('b', 0, type=int)
bar = server.get_build_console_output(a, int(b))
return jsonify(result=bar)
And here is the buildinfo.html:
{% extends "base.html" %}
{% block content %}
<script type="text/javascript" src="{{ url_for('static', filename='jquery-1.12.0.min.js') }}"></script>
<script type="text/javascript">
var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
$(function() {
$('a#load').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/_test', {
a: $('{{job_id}}'),
b: $('{{job_number}}')
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
<div class="col-md-10">
<h1>Build Info</h1>
<br>
<p>retrieving {{job_id}}, build number {{job_number}}</p>
<br>
<p>{{buildinfo}}</p>
<br>
<span id="result">?</span>
go
</div>
{% endblock %}
You're feeding a HTML elements to the ajax call, when you should be passing values. Change this:
a: $('{{job_id}}'),
b: $('{{job_number}}')
to this:
a: {{job_id}},
b: {{job_number}},
...
I'm not sure about the types you're sending, if you need to send strings- wrap quotes around the double-moustache, but this should get you going. See here for a similar issue.
For anyone in the same boat, I am able to refresh a Flask value using the following. I may update this answer to include clearInterval() once the build is complete. Thanks to GG_Python for pointing out my mistake.
app.py :
#app.route('/buildinfo/<job_id>/<job_number>', methods=['GET', 'POST'])
def buildInfo(job_id, job_number):
try:
console_output = server.get_build_console_output(job_id, int(job_number))
return render_template("buildinfo.html", buildinfo=console_output, job_id=job_id, job_number=job_number)
except Exception as e:
return render_template("buildinfo.html", error=str(e))
#app.route('/_test')
def foo():
a = request.args.get('a', None, type=str)
b = request.args.get('b', 0, type=int)
bar = server.get_build_console_output(a, int(b))
return jsonify(result=bar)
buildinfo.html :
{% extends "base.html" %}
{% block content %}
<script type="text/javascript" src="{{ url_for('static', filename='jquery-1.12.0.min.js') }}"></script>
<script type="text/javascript">
var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
<script type="text/javascript">
setInterval(function() {
$.getJSON($SCRIPT_ROOT + '/_test', {
a: "{{job_id}}",
b: {{job_number}}
}, function(data) {
$("#result").text(data.result);
});
return false;
}, 3000);
</script>
<div class="col-md-10">
<h1>Build Info</h1>
<br>
<p>retrieving {{job_id}}, build number {{job_number}}</p>
<br>
<p id="result">{{buildinfo}}</p>
<br>
</div>
{% endblock %}
I'm trying to read json from my Web Service.
I get an error when I try to read teh file form the Web Service.
This is my controller:
var myApp = angular.module('myApp',[]);
myApp.controller('ShowServers', function($scope, $http) {
$http.get('http://localhost/espaidiscos/WebService/ws.php/servidors').
success(function(data, status, headers, config) {
$scope.servers = data;
console.log("work");
}).
error(function(data, status, headers, config) {
// log error
console.log("don't work");
});
});
The html:
<html ng-app='myApp'>
<header>
<script src="./assets/js/angular.min.js"></script>
</header>
<body>
<div ng-controller="ShowServers">
<ul>
<li ng-repeat="server in servers">
{{ server.nom }}
</li>
</ul>
</div>
<!--<div ng-controller="GreetingController">
{{ greeting }}
</div>-->
</body>
<!--<script src="./assets/js/angular.min.js"></script>-->
<script src="./assets/js/controller.js"></script>
<!--<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>-->
</html>
I can't get any value on the browser. I'm very newbie, any help would be grateful.
Edit:
This is What I get form the Web Service on this URL:
{"servers": [{"idServidors":"1","nom":"file01","ip":"10.0.0.170"},{"idServidors":"2","nom":"dc","ip":"10.0.0.5"}]}
Edit v2:
I tryied with SoapUI and this is what my web service is returning me:
<html>
<head>
<meta content="HTML Tidy for Java (vers. 26 sep 2004), see www.w3.org" name="generator"/>
<title/>
</head>
<body>{"servers": [{"idServidors":"1","nom":"file01","ip":"10.0.0.170"},{"idServidors":"2","nom":"dc","ip":"10.0.0.5"}]}</body>
</html>
Can the problem comes from here? Don't should be a simple json without body tag and other stuff?
EDIT v3:
Now my web service is working fine and returns a truly json response. I don't get any error on the js chrome console.
This is how my html and angular looks now:
<html ng-app='myApp'>
<header>
<script src="./assets/js/angular.min.js"></script>
</header>
<body>
<div ng-controller="ShowServers">
<ul>
<li ng-repeat="server in servers">
{{ server.nom }}
</li>
</ul>
</div>
<!--<div ng-controller="GreetingController">
{{ greeting }}
</div>-->
</body>
<!--<script src="./assets/js/angular.min.js"></script>-->
<script src="./assets/js/controller.js"></script>
<!--<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>-->
</html>
var myApp = angular.module('myApp',[]);
$http.get('http://localhost/espaidiscos/WebService/ws.php/servidors').success(function(data, status, headers, config) {
$scope.servers = data;
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
}).
error(function(data, status, headers, config) {
// log error
console.log("Error");
});
});
SOLVED:
I copyed the example on w3schools site: http://www.w3schools.com/angular/angular_http.asp
<script>
var MyApp = angular.module('myApp', []);
MyApp.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost/espaidiscos/WebService/ws.php/servidors")
.then(function(response) {
$scope.servers= response.data.servers;
});
});
</script>
It looks like 2 things could be happening. The first is the variable servers isn't instantiated when the ng-repeat runs.
The second is servers doesn't actually have a nom attribute.
$scope.servers = [];
//HTTP Request
Also, print out the servers variable from request to make sure you are getting what you think.
EDIT:
You are making $scope.servers equal to the servers object. You should make it equal data.servers. ng-repeat is only going to work over an array.
EDIT2:
If you're getting an error in the error callback, you must print out the servers response to try and debug it. Without seeing this information I can only guess at what's happening. If you can post the URL in your browser and get JSON fine, but when you try it from javascript, you get an error, then it might have something to do with the response-type. The browser will use a response-type of HTML where from Angular I believe the response-type will be JSON by default. Your server might error out if it doesn't know how to handle the latter.
EDIT3
var myApp = angular.module('myApp',[]);
myApp.controller('ShowServers',function($scope,$http,GetServers){
GetServers.simGetServers($scope);
});
myApp.factory('GetServers', function($http,$timeout){
var simGetServers = function(scope){
$timeout(function(){
data = {"servers": [{"idServidors":"1","nom":"file01","ip":"10.0.0.170"},{"idServidors":"2","nom":"dc","ip":"10.0.0.5"}]}
scope.servers = data.servers;
},200)
};
var getServers = function(scope){
$http.get('http://localhost/espaidiscos/WebService/ws.php/servidors').success(function(data, status, headers, config) {
scope.servers = data.servers;
}).
error(function(data, status, headers, config) {
console.log(data);
});
};
return {
getServers: function(scope){
getServers(scope);
},
simGetServers: function(scope){
simGetServers(scope);
}
}
});
<html>
<header>
<title>StackOverflow Question Response</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</header>
<body ng-app="myApp">
<div ng-controller="ShowServers">
<ul>
<li ng-repeat="server in servers" ng-cloak>
{{ server.nom }}
</li>
</ul>
</div>
<script src="index.js"></script>
</body>
</html>
You put your script outside of the body tag!
The error you show from your web browser's console implies that the server is not providing a JSON object. Check your web service to make sure that it is proving the object the way you expect.