I just started out with AngularJS, and I have a question regarding $http service and receiving data from web server, I made this simple script that was supposed to get JSON from Steam's DotA2 API but for some reason it's not getting data, here are index.html and script.js respectively:
<html ng-app="steamPowered">
<head>
<script data-require="angular.js#1.3.0-beta.5" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script src="script.js"></script>
<title>
Angular
</title>
</head>
<body ng-controller="MainController">
<div>
<p>{{errx}}</p>
</div>
<div>
<p>Player ID: {{levat.result.players[0].account_id}}</p>
</div>
</body>
</html>
script.js
(function() {
var nesscafe = angular.module("steamPowered", []);
var MainController = function($scope, $http) {
var apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
var matchID = prompt("Enter match ID: ")
var returnedObject = function(response) {
$scope.levat = response.data;
}
var onError = function() {
$scope.errx = "ERROR: https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?match_id=" + matchID + "&key=" + apikey;
} $http.get("https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?match_id=" + matchID + "&key=" + apikey)
.then(returnedObject, onError);
}
nesscafe.controller("MainController", MainController);
}());
Related
I am learning Angular JS. I am trying to create a mock portal that displays Daily Messages. I have stored my daily messages in a database table.
create table DailyMsg(Sno int primary key, msg varchar(max));
Then I created a service using factory in AngularJS.
public class DailyMsgsController : Controller
{
private amenEntities1 db = new amenEntities1();
// GET: DailyMsgs
public ActionResult Index()
{
return Json(db.DailyMsgs.ToList(),JsonRequestBehavior.AllowGet);
}
}
I tested the URL and it works fine, it returns the expected data in the JSON format
https://localhost:44329/DailyMsgs
Now, I wanted to display this data on my HomePage. But it doesn't work. On inspecting the page it shows me the error
Error: $http:badreq
Bad Request Configuration
Http request configuration url must be a string or a $sce trusted object. Received: undefined
My Controller
var myApp = angular.module('myApp', []);
//Daily Messages Service Function
myApp.factory('DailyMsgService', function ($http) {
DailyMsgObj = {};
DailyMsgObj.DisplayDailyMsg = function () {
var Msg;
Msg = $http({method: 'GET', URL: '/DailyMsgs/Index'}).
then(function (response){
return response.data;
});
return Msg;
}
return DailyMsgObj;
});
myApp.controller('HomePageController', function ($scope, DailyMsgService) {
DailyMsgService.DisplayDailyMsg().then(function (result) {
$scope.DailyMsg = result;
});
});
My HomePage
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div ng-controller="HomePageController">
{{DailyMsg}}
</div>
</body>
</html>
<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<script src="../AngularControllers/HomePageController.js"></script>
I am trying to search a local Solr core and am getting no response using getJSON. I know the URL works and returns a response but the getJson function seems to return null.
<!DOCTYPE html>
<html>
<head>
<title>Ray Search</title>
</head>
<body>
Document ID:<br>
<input id="query" type="text" name="document_ID"><br>
<button onclick="searchSolr();">Search</button>
<div id="results">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type='text/javascript'>
function searchSolr() {
var searchStr = $('#query').val();
if (searchStr.length == 0) {
return;
}
var searchURL = "http://localhost:8983/solr/Ray-Docs/select?q=*&wt=json&json.wrf=on_data";
$.getJSON(searchURL, function (result) {
var docs = result.response.docs;
var total = 'Found ' + result.response.numFound + ' results';
$('#results').prepend('<div>' + total + '</div>');
});
}
</script>
</html>
Did you try invoking getJSON like below?
jQuery.getJSON(sourceURL).done(function(returnData){
//Data Processing
});
I got problem with my angular ... I currently working for a simple chat broadcast with socket io, but why my array object won't show up in html after socket io catch the emit
Here's my code for index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app='BaseModule'>
<div ng-controller="ChatController">
<input type='number' name='sender' ng-model='sender' />
<input type='number' name='to' ng-model='to' />
<textarea name='message' ng-model='message'></textarea>
<button type='button' ng-click='sendMessage()'>send it</button>
<pre>{{ conversation }}</pre>
</div>
</body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="base.js"></script>
<script></script>
</html>
and here's the code for my base.js
var app = angular.module('BaseModule', []);
app.run(function($rootScope) {
});
app.controller('ChatController', ChatController);
function ChatController($scope){
var self = window.location.hostname;
var socket = io.connect('http://' + self + ':8890');
$scope.to = '';
$scope.message = '';
$scope.conversation = [];
socket.on('connect', function () {
$scope.sendMessage = function(){
var message = {
to: $scope.to,
sender: $scope.sender,
message: $scope.message
};
socket.emit('chat', message);
};
});
socket.on('broadcast', function(data){
$scope.conversation = data;
console.log($scope.conversation);
});
}
and this is my gulpfile.js
var gulp = require('gulp');
gulp.task('socketio', function(){
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var conversations = [];
server.listen(8890);
io.on('connection', function (socket) {
socket.on('chat', function(data){
conversations.push(data);
console.log(conversations);
socket.emit('broadcast', conversations);
});
});
});
as you can see I was running my socket io via gulp, it's worked actually, but the problem is with $scope.conversation in my index.html, why won't it change ?
It might be an issue with $scope binding, so try by adding the $scope.$digest(); after the $scope.conversation = data;
I am trying to create an API using a local server for testing. The ROUTES are working and I can add data to the OBJ using the URL from the browser. The issue is when I try to 'POST' the data through the HTML. I am getting back a 404 error. I developing using node.js and Express. What am I doing wrong?
JS on the server side
app.get('/add/:word/:score?', addWord);
//Function to request and send back the data
function addWord(request, response) {
var data = request.params;
var word = data.word;
var score = Number(data.score);
var reply;
if (!score) {
var reply = {
msg: 'Score is required'
}
response.send(reply);
} else {
words[word] = score;
// Transforms javascript object into raw data correctly idented with null, 2
var data = JSON.stringify(words, null, 2);
fs.writeFile('words.json', data, finished);
function finished(err) {
console.log('Writting');
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
}
POST method JS
$('#submit').on('click', function submitWord() {
var word = $('#fieldWord').val();
var score = $('#fieldScore').val();
$.ajax({
type: 'POST',
url: '/add/' + word + "/" + score,
success: function (newOrder) {
$list.append('<li>name: ' + newOrder.word + newOrder.score + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial API with node.js</title>
<script type="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p>
Word: <input type="text" id="fieldWord"><br/>
Score:<input type="text" id="fieldScore"><br/>
<button type="button" id ="submit">Submit</button>
<ul id="list">
</ul>
</p>
</body>
<script type="text/javascript" src="sketch.js"></script>
</html>
Thank you in advance.
Javascript newbie here. I have a javascript function that works nested in an html file, I import an external library abaaso, then declare the function and then call it:
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<script src="abaaso.js"></script>
</head>
<body>
<script>
var baseurl = "https://example.com";
var baseapi = baseurl + "/api/v1/";
var api_username = "user";
var api_key = "key";
var credentials = "?api_username=" + api_username + "&api_key=" + api_key;
var rawdata = {};
(function ($$) {
/* login */
login = function(username, password) {
var calledUrl = baseapi + "user/login/" + credentials;
calledUrl.post(
function (content) {
/*console.log("success" + JSON.stringify(content, null, 4));*/
},
function (e) {
console.log("it failed! -> " + e);
},
{
"username": username,
"password": password
},
{"Accept" : "application/json"}
);
}
})(abaaso);
login('test#example.com', 'passwd');
</script>
</body>
</html>
I want to put it in an external .js file and import it and only use the call to the function login('test#example.com', 'passwd');. I don't want to import abaaso from the html file but from the new .js.
How can I do that? Is there a particular structure to respect? Do I need to create a global function to the js file?
I don't want to import abaaso from the html file but from the new .js.
You can't do that. However, you can import both abaaso and the new .js:
<head>
<title>title</title>
<script src="abaaso.js"></script>
<script src="new.js"></script>
</head>