Since I am fairly new to web development, this might very well be a very easy to solve question. Unfortunately I am not able to solve this myself as I have no clue on where to search.
Currently I'm trying to get data out of an ASP.NET Web API that is running on my local machine. To get this data I've written a small piece of JavaScript using AngularJS:
function MainController($scope, $http) {
$http.get("http://localhost/DBLayerDLL/api/tablets/1005").
then(function(response) {$scope.data=response;},
function(response){$scope.data=response;});
}
The HTML page that is used, is also very simple:
<!DOCTYPE html>
<html ng-app>
<head>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script src="scripts/main.js"></script>
</head>
<body ng-controller="MainController">
<h1>Hello World!</h1>
<div>
<div>Data: {{data}}</div>
</div>
</body>
</html>
The action of the controller in my Web API is implemented as follows:
[RoutePrefix("api/tablets")]
public class TabletsController : ApiController
{
[Route("{ID}")]
[HttpGet]
public TabletRecord GetTablet(int ID)
{
TabletRecord tablet = new TabletRecord();
tablet.LoadFromID(ID);
return tablet;
}
}
The problem lies within the response I get from the HTTP request. When printed on the page it looks like this:
{"data":"","status":0,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"http://localhost/DBLayerDLL/api/tablets/1005","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":""}
Which is not correct, as I know that my API will return data. It gets even weirder for me when I use Fiddler to see what is going on. Within Fiddler I can see the request and see that the response is completely different from what I see on my web page:
Due to my lack of knowledge and experience I don't know what is going on...
Is there any thing I am doing wrong in my JavaScript?
Should I do something else within the HTML page?
Or is there any special thing that I need in my Web API?
Any help or thoughts are highly appreciated!
After spending quite some more time on this I've found a couple of things were needed to solve my problem:
I've noticed that I had to enable CORS on my Web API in order for the JavaScript to be able to make requests to my Web API. I've came to this via this link, I just followed the steps as explained to get it up and running.
I've also discovered at first that I can also get my data using the general XMLHttpRequest object available in JavaScript. By first getting my data to display using this method, I've also discovered the next item:
The response object returned by the $http.get method is actually the object that is directly returned by my Web API. So I can just use the defined properties to display the required data.
On normal php i get the angular variables with
$data = file_get_contents("php://input");
you should look if
print_r($data);
contains what u need.
Related
Me an my team are currently working on a software project at university and my present task is to bind our desktop javafx application with Facebook.
Basically I have an fxml method in a controller that is called when the user hits a "Share" button in my GUI. In the method I'd like to simply open up my .html file using a WebView:
#FXML
public void shareFacebookClicked() throws Exception{
// Setting up the webview
WebView webView = new WebView();
final WebEngine webEngine = webView.getEngine();
webEngine.setJavaScriptEnabled(true);
// Read the html file and let the web engine load it.
File file = new File(getClass().getClassLoader().getResource("facebook.html").toURI().getPath());
webEngine.load(file.toURI().toURL().toString());
Stage stage = new Stage();
stage.initOwner(this.stage);
stage.setScene(new Scene(webView, 1000, 800));
stage.show();
}
There is no problem with it, my "facebook.html" file is loaded and displayed correctly (well, almost correctly) in a web view.
The actual problem is that I'm constantly getting the 191 Facebook error saying that the link is not owned by the application. Since there are tons of posts and questions on this around the Internet (and yes I checked and read all of them) here are the things that I'm already aware of:
I registered my application on the Facebook Developer site. I know about the AppID and Secret
I know that this error mainly comes from the fact that people forget to set their website URL and domain in the Settings. The problem is that I don't have a website. I just have a simple .html file which I'd like to use in a web view inside of javafx. However, I tried all possible combinations advised on stackoverflow, facebook help centre and other forums which include: Setting website URL to http://localhost/, domain to localhost, enabling Embedded browser OAuth Login, setting the redirect URI to localhost too, etc.
I assume that my goal could be achieved by using RESTfb, Facebook4j or Graph API. When I tried those I had to stop because I faced problems with the user authentication plus I thought this current option would be the easiest way (considering this feature has LOW-priority in our software).
None of this solved my problem therefore I've given up researching the answer and decided to post my very own personal question.
In my opinion there must be some error in the .html file and/or I completely misunderstand something in the way this works. The .html file:
<html>
<head>
<title> Share on Facebook </title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js"></script>
<script src="https://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#shareonfacebook').click(function (e) {
FB.ui({
appId: 'MY_APP_ID',
display: "popup",
method: "feed",
name: "Test",
link:"",
caption:"Test",
description: "Test",
});
});
});
</script>
</head>
<body>
<div id="fb-root"></div>
<button id="shareonfacebook" >Share</button>
<script>
FB.init({
appId : 'MY_APP_ID'
});
</script>
</body>
</html>
Partially I have this code from a tutorial site. Theoretically it should work. All I want is a dialog to come up where the user can publish the results of the workout he/she completed using our software. Currently when the .html file is opened up there is a simple button to click. This and all the "Test" strings inside of the javascript are only for testing. I just want to achieve that I can post something on my wall. The next step would be of course to somehow set the posting text dynamically etc.
Please tell me what I'm doing wrong or how I should approach the whole thing. Like I said, the task is minimal therefore it shouldn't be that difficult but I've been sitting in front of my laptop for 2 days without any success. I'm ready to post more code or give more information if it's needed.
Thank you for the help in advance!
I am developing a simple Tic Tac Toe on Google App engine using cloud endpoints. My API name is tictactoe2D.
I have only 1 endpoint method by the name tictactoe2D.compute2DMove() in my API which I have tested in the APIs explorer, and is working absolutely fine.
Now I am working to create the front end of the game, and using Google APIs JavaScript Client library to communicate with my endpoint method. I have followed exactly the same procedure as shown in the Getting Started page, which is a complete tutorial on using the library.
Here is code snippet from board.html, which loads the Javascript library-
<head>
<title>Tic Tac Toe 3D</title>
<meta http-equiv="content-type" charset="utf-8" content="text/html"/>
<link href="css/main.css" rel="stylesheet" type="text/css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onLoadCallback"></script>
<script type="text/javascript">
function onLoadCallback() {
gapi.client.setApiKey('AIzaSyB7p7mH_vZGgtrbF4ntmKN2nBcsRyRFY1w');
gapi.client.load('tictactoe2D', 'v1');
}
</script>
<script type="text/javascript" src="js/render.js"></script>
</head>
And here is the code from render.js, which add the functionality to deal with click event of all squares, and also communicates with my endpoint method-
$(document).ready(function() {
$("#board td").click(function() {
$(this).html("X");
var boardString = [];
var buttons = document.querySelectorAll('td');
for (var i=0; i<buttons.length; i++) {
boardString.push(buttons[i].innerHTML);
}
boardString.join('');
gapi.client.tictactoe2D.compute2DMove({'state': boardString}).execute(function(resp) {
document.write(resp.result.state);
});
});
});
Here is the JSFiddle for the whole code.
Problem occurs when I try to click one of the squares on the game board. Unexpectedly, nothing happens.
I opened up the JavaScript console in Chrome, and found out that the console showed the following error whenever I click on a square-
Uncaught TypeError: Cannot read property 'compute2DMove' of undefined
I have not been able to figure out why is this happening, and how can I fix it. Can anybody please help me out?
Thankyou very much in advance.
I ended up fixing the bug myself after I observing a new error on the JS console- The error was-
Failed to load resource: The server responded with a status of 403 (Forbidden)
I checked the JSON object that the server returned, and the object was something like this-
{"error":{"errors":[{"domain":"global","reason":"sslRequired","message":"SSL is required to perform this operation."}],"code":403,"message":"SSL is required to perform this operation."}}
After seeing this, I guessed that a secure connection(HTTPS) was not used to connect to the app, and that is why server was not loading the required data. To fix this, I needed to mandate that a secure connection be used every time the app is loaded. For this, I added the following tag to web.xml-
<security-constraint>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
I updated my app on appspot, and checked the JS console. There was no error there, and my endpoint method executed too. I hope this information if helpful to anyone who faces a similar issue.
Also, I found out that the gapi library had some stability issues in the past, and the best way to safeguard your API calls against any possible flaws is to construct a REST request using gapi.client.request(), instead on making JSON-RPC requests. (see, Constructing REST requests using gapi.client.request). Constructing REST requests might be lengthy and cumbersome, but is safe too.
Here is a link to their API documentation
I would like to practice web programming by creating a bitcoin price ticker from scratch. My plan is to serve a script that makes api calls to exchanges to display the data. This will mean I only have to serve the script, not handle the data server-side.
I know that part of programming is learning from documentation, but the docs from bitfinex are very sparse and I couldn't find a tutorial.
I created an index.html to test my javascript. It returns a console error:
XMLHttpRequest cannot load https://api.bitfinex.com/v1/pubticker/:last_price.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
Here is the full index.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>
<body>
<script>
$.getJSON("https://api.bitfinex.com/v1/pubticker/:last_price",
function(data, status){
alert("price: "+data +" status: " + status);
}
)
</script>
Thank you stack exchange
</body>
You can't — at least, not with Javascript. That API is not configured to allow calls from Javascript running on other web sites. You will need to call this API from a script running on your web server.
(Also, for what it's worth, the :symbol token in the URL is supposed to be replaced with the symbol of the ticker you're trying to look up, e.g. /v1/pubticker/BTCUSD for BTC/USD exchange prices.)
If you run a webserver with SSL on it (as Duskwuff said, "You will need to call this API from a script running on your web server.") then you can deploy the following file to it:
<?php
$func = $_GET['fn'];
if(in_array($func,array('getBfx')))
{
$func();
}
function getBfx()
{
$a = $_GET['api'];
echo "objData = ".file_get_contents($a);
}
?>
Then you can include the script from the URL to which you deployed it, with ?func=getBfx&api=https://api.bitfinex.com/v1{Whatever} tacked onto the end of it. I didn't have to escape that URL, but you might.
I need to intercept a javascript call to window.external.notify which is returning a security token string that I need to get into my objective C code. The javascript is being executed in a UIWebView. The script there looks like:
<script type="text/javascript">
try{
window.external.notify('{<extremely long dictionary as a JSON string>}');
}
catch(err){
alert("Error ACS50021: window.external.notify is not registered.");
}
</script>
I need to somehow get the JSON dictionary into a string in objective C. I've tried going through the method here: http://www.stevesaxon.me/posts/2011/window-external-notify-in-ios-uiwebview/; but it just seems to interfere with the rendering of the html/javascript page and also not capture the string (I don't have a handy acs identifier to check for to know I'm intercepting the right call). Other similar questions have been asked, but I haven't been able to get any working, many seem extremely hackish, and they are usually quite out of date. I've tried accessing the webview's html content, but the token isn't present there, because it's only sent through window.external.notify, which errors out with the alert that it isn't registered.
I know there's now a native JS->objC bridge in iOS 7, and I only need to support iOS 7+, but I've never used it and I can't seem to get that up and running either. It also appears to be mainly for having your own JS source files as part of your app, and not for communicating with a server through a UIWebView, but if I'm wrong about that, let me know.
Try this method.Here the page is redirected and the token is loaded using receive data method.
I build a website focussing on loading only data that has to be loaded.
I've build an example here and would like to know if this is a good way to build a wegpage.
There are some problems when building a site like that, e.g.
bookmarking
going back and forth in
history SEO (since the content is basically not really connected)
so here is the example:
index.html
<html>
<head>
<title>Somebodys Website</title>
<!-- JavaScript -->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="pagecode.js"></script>
</head>
<body>
<div id="navigation">
<ul>
<li>Welcome</li>
<li>Page1</li>
</ul>
</div>
<div id="content">
</div>
</body>
</html>
pagecode.js
var http = null;
$(document).ready(function()
{
// create XMLHttpRequest
try {
http = new XMLHttpRequest();
}
catch(e){
try{
http = new ActiveXObject("MS2XML.XMLHTTP");
}
catch(e){
http = new ActiveXObject("Microsoft.XMLHTTP");
}
}
// set navigation click events
$('.nav').click(function(e)
{
loadPage(e);
});
});
function loadPage(e){
// e.g. "link_Welcome" becomes "Welcome.html"
var page = e.currentTarget.id.slice(5) + ".html";
http.open("POST", page);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function(){changeContent(e);};
http.send(null);
}
function changeContent(e){
if(http.readyState == 4){
// load page
var response = http.responseText;
$('#content')[0].innerHTML = response;
}
}
Welcome.html
<b>Welcome</b>
<br />
To this website....
So as you can see, I'm loading the content based on the IDs of the links in the navigation section. So to make the "Page1" navigation item linkable, i would have to create a "Page1.html" file with some content in it.
Is this way of loading data for your web page very wrong? and if so, what is a better way to do it?
thanks for your time
EDIT:
this was just a very short example and i'd like to say that for users with javascript disabled it is still possible to provide the whole page (additionally) in static form.
e.g.
<li>Welcome</li>
and this Welcome.html would contain all the overhead of the basic index.html file.
By doing so, the ajax using version of the page would be some kind of extra feature, wouldn't it?
No, it isn't a good way to do it.
Ajax is a tool best used with a light touch.
Reinventing frames using it simply recreates all the problems of frames except that it replaces the issue of orphan pages with complete invisibility to search engines (and other use agents that don't support JS or have it disabled).
By doing so, the ajax using version of the page would be some kind of extra feature, wouldn't it?
No. Users won't notice, and you break bookmarking, linksharing, etc.
It's wrong to use AJAX (or any javascript for that matter) only to use it (unless you're learning how to use ajax which is diffrent matter).
There are situations where the use of javascript is good (mostly when you're building a custom user interface inside your browser window) and when AJAX really shines. But loading static web pages with javascript is very wrong: first, you tie yourself with a browser that can run your JS, second you increase the load on your server and on the client side.
More technical details:
The function loadPage should be re-written using jquery : $post(). This is a random shot, not tested:
function loadPage(e){
// e.g. "link_Welcome" becomes "Welcome.html"
var page = e.currentTarget.id.slice(5) + ".html";
$.post( page, null, function(response){
$('#content')[0].innerHTML = response;
} );
}
Be warned, I did not test it, and I might get this function a little wrong. But... dud, you are using jQuery already - now abuse it! :)
When considering implementing an AJAX pattern on a website you should first ask yourself the question: why? There are several good reasons to implement AJAX but also several bad reasons depending on what you're trying to achieve.
For example, if your website is like Facebook, where you want to offer end-users with a rich user interface where you can immediately see responses from friends in chat, notifications when users post something to your wall or tag you in a photo, without having to refresh the entire page, AJAX is GREAT!
However, if you are creating a website where the main content area changes for each of the top-level menu items using AJAX, this is a bad idea for several reasons: First, and what I consider to be very important, SEO (Search Engine Optimization) is
NOT optimized. Search engine
crawlers do not follow AJAX requests
unless they are loaded via the
onclick event of an anchor tag.
Ultimately, in this example, you are
not getting the value out of the rich
experience, and you are losing a lot
of potential viewers.
Second, users will have trouble bookmarking pages unless you implement a smart way to parse URLs to map to AJAX calls.
Third, users will have problems properly navigating using the back and forward buttons if you have not implemented a custom client-side mechanism to manage history.
Lastly, each browser interprets JavaScript differently, and with the more JavaScript you write, the more potential there is for losing cross browser compatibility unless you implement a framework that such as jQuery, Dojo, EXT, or MooTools that handles most of that for you.
gabtub you are not wrong, you can get working AJAX intensive web sites SEO compatible, with bookmarking, Back/Forward buttons (history navigation in general), working with JavaScript disabled (avoiding site duplication), accessible...
There is one problem, you must get back to server-centric.
You can get some "howtos" here.
And take a look to ItsNat.
How about unobtrusivity (or how should I call it?)?
If the user has no javascript for some reason, he'll only see a list with Welcome and Page1.
Yes it's wrong. What about users without JavaScript? Why not do this sort of work server-side? Why pay the cost of multiple HTTP requests instead of including the files server-side so they can be downloaded in a single fetch? Why pay the cost of non-JavaScript enabled clients not being able to view your stuff (Google's spider being an important user who'll be alienated by this approach)? Why? Why?