I'm trying to use long polling within an angularjs app. I have the long polling within a controller that is updating a scope variable that is referenced within the view.
When I step through the code the polling is occurring and the expected data is being returned but the view is never being updated.
longpolltest.js
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function($scope, $timeout) {
$scope.value = 1;
function poll() {
var d = new Date();
var n = d.getTime();
$scope.value++;
$.ajax({
type: 'GET',
url: '/gs/async?millis=' + n,
contentType: "application/json; charset=utf-8",
async: true,
cache: false,
success: function(data) {
var obj = jQuery.parseJSON(data);
if (obj.type == 'ServerTime')
$scope.myTime = object.Data.Time;
setTimeout("poll()", 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + textStatus + " " + errorThrown);
setTimeout("poll()", 10000);
}
});
}
poll();
});
longpolltest.html
<!DOCTYPE html>
<html>
<head lang="en">
<!-- jQuery JavaScript -->
<script src="js/ext/jquery-1.12.0.min.js"></script>
<!-- angular library -->
<script src="js/ext/angular/angular.min.js"></script>
<script src="js/ext/angular/angular-route.min.js"></script>
<script src="js/longpolltest.js"></script>
<meta charset="UTF-8">
<title>Long poll test</title>
</head>
<body ng-app="myApp">
<div>
<div ng-controller="MyController">
<p>
Time: {{myTime}}
Poll#: {{value}}
</p>
</div>
</div>
</body>
Any ideas why the view would not be getting updated would greatly be appreciated.
Thanks in advance.
Some general advice:
don't use jquery http method. You should prefer $http angular service.
don't use timeout function.You should prefer $timeout angular service.
don't invoke http remote services inside your controller. You should create a dedicated service.
A further improvement can be to use the $interval service
Related
I am currently new in Cognitive services. Yesterday I tried Computer vision API where I got different JSON response for the same image in the API Testing console to that when I used the javascript code in my browser. I have enclosed my javascript code and the screenshot of the two different responses.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var myKey = "my key";
var myBody = {url:"http://activeforlife.com/wp/wp-content/uploads/2015/05/co-ed-kids-playing-soccer.jpg"}
$(function() {
var params = {
// Request parameters
"maxCandidates": "1",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
},
type: "POST",
// Request body
data: JSON.stringify(myBody),
})
.done(function(data) {
document.getElementById("ans").innerHTML = JSON.stringify(data);
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
<h4 id="ans"></h4>
</body>
</html>
Screenshot for the different outputs
The Cognitive Service Vision API will perform different visual classifications depending on the visualFeatures query parameter. You can find more details here.
If you don't specify any features, you are performing the equivalent of visualFeatures=Categories (your example). The console appears to have been executed with visualFeatures=Description. You can set the feature list in your param object.
I have template Test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name = "viewport" content = "width = device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
</head>
<body >
<h1>Stock Quotes AutoSuggest </h1>
<br><br>
<input style="width:800px; height:20px;" id="txtTicker" class="x"/>
<script type="text/javascript">
var YAHOO = {
Finance: {
SymbolSuggest: {}
}
};
$(".x").autocomplete({
source: function (request, response) {
var query=request.term;
$.ajax({
type: "GET",
url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc",
data: {query: query,region:'US',lang:'en-US'},
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "YAHOO.Finance.SymbolSuggest.ssCallback",
});
// call back function
YAHOO.Finance.SymbolSuggest.ssCallback = function (data) {
var suggestions = []; //alert(JSON.stringify(data.ResultSet.Result));
$.each(data.ResultSet.Result, function(i, val) {
suggestions.push(val.symbol+ " "+ val.name);
});
response(suggestions);
}
},
minLength: 1,
select: function (event, ui) {
//alert(ui.item.value.split("#")[1]);
$(this).val(ui.item.value.split(" ")[0]);
$("#stockvalue").val(ui.item.name);
return false;
},
});</script>
</body>
</html>
Javascript uses for autosuggest ticker names. After user input some letter in input field it sends ajax request to yahoo finance and should show the result.
If i open this html directly in browser - it works fine and shows some suggestions. But after i use it in my django project it shows nothing.
My views.py:
def home(request):
return render(request, 'Test.html')
What i found out in firefox console:
1) If i open html directly:
after placing a letter in input field JS sends request to YAHOO.Finance (the full link for letter a: http://d.yimg.com/autoc.finance.yahoo.com/autoc?callback=YAHOO.Finance.SymbolSuggest.ssCallback&query=a®ion=US&lang=en-US&_=1467262652424) with method GET and it's working good, we have an answer in json.
2) If we use Django to render this template:
It sends request to YAHOO too (the full link for letter a: http://d.yimg.com/autoc.finance.yahoo.com/autoc?callback=YAHOO.Finance.SymbolSuggest.ssCallback&query=a®ion=US&lang=en-US&_=1467263364507) but the status is 400 Bad Request. Inside the answer from yahoo i see this: /**/YAHOO.Finance.SymbolSuggest.ssCallback({"error":{"result":null,"error":{"code":"request-error","description":"Unauthorized JSONP request"}}});
What could be wrong?
I found answer for my question:
all you need is to add this in head:
<meta charset="UTF-8" name="referrer" content="no-referrer">
I have written a nodejs plugin in C++ and I am trying to call it from within a locally hosted webpage with jQuery. I have read that I can't make a direct call to nodejs because of the same origin policy so I should use jsonp. Note: I am pretty new to jquery, nodejs and json(p), but I am feeling adventurous. I am now using the following code:
node_test.js:
var mylib = require("./mylibrary");
var http = require("http");
http.createServer(function(req, res) {
console.log("Received request: " + JSON.stringify(req.url));
res.writeHead(200, {"Content-type": "text/plain"});
res.end('_testcb(\'{"message": "' + mylib.my_awesome_function() + '"}\')');
}).listen(1337);
index.html:
index.html:
<DOCTYPE HTML>
<html>
<head>
<title>
NodeJS test
</title>
<link rel='stylesheet' type='text/css' href='style.css'/>
<script type='text/javascript' src='jquery.js'></script>
</head>
<body>
<div id="test"></div>
<script>
$(document).ready(function() {
$.ajax({
url: "http://127.0.0.1:1337/",
dataType: "jsonp",
jsonpCallback: "_testcb",
cache: false,
data: "test_data",
timeout: 5000,
success: function(data) {
$("#test").append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
});
</script>
</body>
</html>
If I run node node_test.js and view index.html in my browser my function gets called. However, I would like to be able to execute multiple functions from my own nodejs library. I thought of somehow parsing the data I send to my nodejs app, and run it through a big switch case, a bit like this:
var reply = "";
switch (data) {
case 1:
reply = mylib.my_awesome_function();
break;
case 2:
reply = mylib.my_cool_function();
break;
// repeat for every function I have
}
// send reply
But I am not sure if this is the intended way to do this. Is there a better/smarter way to make multiple calls to nodejs from within jQuery/javascript on a webpage?
I am trying to use breeze to do the same calls that work using angualar's $http. For some reason the $scope does not appear to work in the breeze callback.
Code:
<!DOCTYPE html>
<html ng-app="">
<head>
<meta name="viewport" content="width=device-width" />
<title>App</title>
</head>
<body ng-controller="TextController">
<div>
<p>{{textData1}}</p>
<p>{{textData2}}</p>
<ul>
<li ng-repeat="patient in patients">
<span>{{patient.FirstName}}</span>
</li>
</ul>
</div>
<script src="/scripts/jquery-1.8.2.js"></script>
<script src="/scripts/q.js"></script>
<script src="/scripts/breeze.min.js"></script>
<script src="/Scripts/angular.js"></script>
<script type="text/javascript">
function TextController($scope, $http){
breeze.config.initializeAdapterInstance("modelLibrary", "backingStore", true);
var serviceName = "/api/breeze";
var manager = new breeze.EntityManager(serviceName);
var query = breeze.EntityQuery.from("Patients");
$scope.textData1 = "Waiting..";
$scope.textData2 = "Waiting..";
manager.executeQuery(query).
then(function (data) {
console.log(data);
$scope.textData1 = 'Breeze';
//$scope.patients = [];
//$scope.patients = data;
}).
fail(function(error) {
$scope.textData1 = error.message;
});
$http({ method: 'GET', url: '/api/patients' }).
success(function (data, status, headers, config) {
console.log(data);
$scope.textData2 = 'Angular';
//$scope.patients = [];
//$scope.patients = data;
}).
error(function (data, status, headers, config) {
});
}
</script>
</body>
</html>
In the above code both the angular $http call and the breeze calls return data as I print it to the console. When this is run only the textData2 binding updates to 'Angular' the textData1 binding does not update to 'Breeze'. I'm in the function as the console gets called but the binding does not update. The same thing happens if I try to bind the list of data the the 'patients' reference in the scope. I commented that out to show the simplest version of my problem.
Make sense? Thoughts?
Brian
I'm dealing with an issue that make me crazy. I want to build the pages dynamically, but when the POST success (return from my web service, using $.ajax({ type: "POST",....,onsuccess , ) the onsuccess function called which should build a page.
If I call the onsuccess from the onready directly, it works fine the page appear. but when the onsuccess function called due to return from the web service I can't see the page (The onsuccess func called for sure, I also see that the page element their - using Chrome "Inspect element" ), any one can explain me Why I can't see the page!!!!?!
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" />
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"></script>
</head>
<body>
<script type="text/javascript">
function DebugClient(data, fnSuccess, fnError) {
$.ajax({
type: "POST",
url: "Service/WcaService.asmx/Client_GetInfo",
data: '{"id": ' + data + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: fnSuccess,
error: fnError,
dataFilter: function (data) {
//remove the ādā property inserted by all WCF services (if it exists)
return data.replace(/^\{"d":(.*)\}$/, "$1");
}
});
}
$(document).ready(function () {
//If I call the onSuccess directly from here it works.
DebugClient(currentID, onSuccess, DefaultErrorHandler);
return false;
}
function onSuccess(res) {
var html = '';
html += '<div data-role="page">';
html += '<div data-role="header">';
html += '<h1>My Title</h1>';
html += '</div>';
html += '<div data-role="content">';
html += '<p>Hello world</p> ';
html += '</div>';
html += '</div>';
jQuery('#divData').html(html);
return false;
});
</script>
<div id="divData">
</div>
</body>
</html>
Your ajax call specifies fnSuccess. Your function is onSuccess.
Further, it looks like the ajax call might be in the global scope, but the onSuccess() function is inside a $(document).ready() callback which means it isn't available in the global scope.
I solved the problem, it is simply using the $(page).appendTo($.mobile.pageContainer) instead of JQuery(XXX).html, I remark the changes in Red for simplicity and few comments in Green , hope this will be useful and helpful, I can't find complete solution for this scenario, so I add it for any one need it.
Thanks guys.
TAG: how to create page in run time according to return value from WEB Service / WCF
Here the complete solution:
http://bit.ly/vjuPSw