How do I change the link JQuery requests relating to the url? - javascript

At the moment I have the top of the code like this:
$.getJSON(' https://api.roleplay.co.uk/v1/player/' + "END-LINK", function(data)
What I want is that the "END-LINK" bit will be the end of my url - for example, if my url is www.link.com/player.html/76561198062083666 I want it to add those numbers at the end to the jquery request so it will get the api "https://api.roleplay.co.uk/v1/player/76561198062083666"

I think what you want is to retrieve the ID from the link and send it to the API.
var endLink = window.location.href.substr(window.location.href.lastIndexOf('/') + 1)
$.getJSON(' https://api.roleplay.co.uk/v1/player/' + endLink, function(data){...})

In order to query your player ID, you would assign it to a local variable, and then pass that local variable to your .getJSON() function just as you have, expect without the quotes:
var end_link = 76561198062083666;
$.getJSON('https://api.roleplay.co.uk/v1/player/' + end_link, function(data) {
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note that I have replaced END-LINK with end_link, as you cannot have hyphens in variable names (the parser will treat it as subtraction).
Also note that you will be unable to retrieve your information through .getJSON(), as RolePlay.co.uk is transmitting a No 'Access-Control-Allow-Origin' header, meaning they disallow people from querying it in accordance with Cross Origin Resource Sharing (CORS).
This is typically handled on the server, but considering you don't have access, you can bypass it by adding the argument --disable-web-security to your browser launcher.
Hope this helps! :)

Obsidian Age told you very well what you can do to solve your problem.
If I'm not wrong, you want to send the local variables from the link to the API, and you can do it in this way:
var endLink = window.location.href.substr(window.location.href.lastIndexOf('/') + 1)
$.getJSON(' https://api.roleplay.co.uk/v1/player/' + endLink, function(data){
console.log(data);
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

connecting javascript to a Web API

I am new to the web development world and I would like to be able to connect an HTML page to a web api through . and I was really not successful in this.
I followed this tutorial to be able to make this connection : http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
All I need is to send some inputs from an HTML page to a web api that takes these parameters and returns an object
I am using this code
$.getJSON("api/GeneratorController/setparameters/"+firstparameter+"/"+secondparameter+"/"+thirdparameter+"/"+fourthparameter+"/"+fifthparameter+"/"+sixthparameter,
function (data) {
alert(data); //never comes here
}).fail(function (jqXHR, textStatus, err) {
alert("All checks are correct, image was not generated. jqXHR = " + jqXHR.valueOf() + " textStatus=" + textStatus + " Error" + err);
});
it always goes into the fail portion , I attached the alert message that comes out of it
Any Reason why it is doing this ?
#smartmeta (I changed the typo , thanks) I followed your advice and here is the output of the alert (as expected , values that I have inserted are displayed):
Your url needs to start with your domain, not 'api/generatorcontroller/...'. If you are developing locally, something like http://localhost:[port]/api/generatorController/....
Also, webApi maps to url verbs, (get, post, put, delete..), not functions like setparameters, unless you have a [name=setparameters] above your get() function.
Also, I am pretty sure you don't have a route setup to handle the url with all those parameters. What you want to look at, as it seems your using jQuery, is jQuery.get documentation. The second example near the bottom shows where to place parameters. WebAPI will check for them in the body if they are not in the query string. so it would end up looking like:
$.getJSON("http://"+window.location.host+"/api/GeneratorController/setparameters", {parameter1: parameter1, parameter2:parameter2 ...});
Well, the first thing to check is to make sure that your server-side function is returning the values you expect. You can do this with Chrome's developer tools or with the Firebug Firefox extension, and I think IE10 has something equivalent, too. Go to the "net" tab, find the request corresponding to your API call, and take a look at what the server responded with.
Please add the line
alert("api/GeneratorController/setparameters/"+firstparemeter+"/"+secondparameter+"/"+thirdparameter+"/"+fourthparameter+"/"+fifthparameter+"/"+sixthparameter)
Then call your script and take the output of the alert into a browser. Then check if your application Handels that route.
By the way I think you have a typo. I guess it should be firstparameter.
I assume you would like to do
"api/GeneratorController?foo=Bar
But when you are new to this, I would suggest that you first try the example like it is. And After that you can start changing setails.
So I found what was the problem with my code
Two things :
1- I shouldn't use the word "Controller" when I call my API ,it should be api/Generator/...
2- the function name needs to start with "get" and not "set" since it "gets" the return value from the api
Thanks everyone!

404 retrieving Twitter followers using JQuery getJSON

I'm just starting to use the Twitter API to retrieve data using jQuery. I've used the API ok to retrieve information about a single user e.g. https://twitter.com/users/show/codinghorror.json
When I try to retrieve all the users that a given user is following, I'm using the same retrieval pattern but am getting a 404 error (it looks like my callback isn't receiving the json object properly, but appending it to the URL somehow)
I'm using the following code:
getTwitterUserFriends: function() {
var user = 'codinghorror';
var url = 'http://api.twitter.com/1/friends/ids.json?screen_name='+user+'?callback=?';
$.getJSON(url, function(data) {
alert('call succeeded' + data.ids);
});
},
In chrome, the console shows the following error:
GET https://api.twitter.com/1/friends/ids.json?screen_name=codinghorror?callback=jQuery15201747908447869122_1324917568956&_=1324917580929 404 (Not Found)
However if I browse to the URL directly https://api.twitter.com/1/friends/ids.json?screen_name=codinghorror then I can see the results object being returned.
I assume I'm doing something simple wrong with my callback, but can't see what it is, as the approach I've used above has worked for other API calls, so any help would be much appreciated!
Your URL syntax is incorrect. The "callback" parameter should be separated by "&", not "?".
var url = 'http://api.twitter.com/1/friends/ids.json?&screen_name='+user+'&callback=?';
You should probably URL-encode the username too:
var url = 'http://api.twitter.com/1/friends/ids.json?&screen_name=' +
escapeURIComponent(user) +
'&callback=?';
Also I'm not sure why you've got a "&" before the "screen_name" parameter.

Obtain forwarded URL from a source URL?

What is a good way to obtain the end URL if given a URL that is being forwarded to another URL?
For example, if I had the shortened URL: http://bit.ly/900913, what is a good way to determine that this ultimately forwards to http://www.google.com?
I'm using javascript. I'm unsure if this can be done somehow using jQuery (doubtful since the end URL probably isn't returning jsonp content) or if there is some kind of web service that I can use.
Thanks!
For bit.ly specifically, you can use the bit.ly API to make a JSONP call using JavaScript to expand the bit.ly URL(s) in question.
Specifically, you'd use the v3/expand call.
Pseudo-code:
var bitlyurl = "http://bit.ly/900913";
$.getJSON("http://api.bitly.com/v3/expand?shortUrl=" + encodeURIComponent(bitlyurl)+"&apikey=...&callback=?", function( bitlydata ){
var endurl = bitlydata.data.expand[0] //looks like this is where the end URL would point
});
Alternately, you could follow the URL on your own server, and use AJAX to check it's values.
So, you'd pass it a URL ($.get("/follow?url="+bitlyurl,function(data){var endurl = data.Location;});, and make a HEAD call to the URL to see where the Location points.
Here's the basics of how you'd do it in PHP:
<?php
$headers = get_headers($_GET["url"],1);
echo json_encode($headers);
?>
Just for fun, I implemented a live end-point on App Engine to check where a URL points. Feel free to use it! The base URL is followtheredirect.appspot.com, and it requires a url parameter and a callback parameter, and returns a location key on the resulting object, when successful.
Sample code:
$.getJSON("http://followtheredirect.appspot.com/?url="+encodeURIComponent('http://bitly.com/hhN7Ol')+"&callback=?",function(data){
var location = data.location;
});
Let me know if you find any bugs :) it might be a bit messy...
Bitly provides a preview service. If you visit http://bit.ly/900913- (notice the hyphen at the end), you'll get a response with the full URL.

script tag hack + how do I communicate after the second level of AJAX

I want to provide an embeddable javascript which will get a script from my server . Which in turn will get some details from the user(the page which which has my embeddable js) and put it back onto my server . How do i go about achieving this .
This is the embeddable js i provide .
<script>
(function() {
read="This is the data which is entered by the user";
var istreet = document.createElement('script'); istreet.type = 'text/javascript'; istreet.async = true;
istreet.src = 'http://xyz.com/a.php;
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(istreet);
})();
</script>
And this is the code on http://xyz.com/a.php
$('<div id="content"></div>').appendTo('body');
$('#content').html('
Some html to inject to the page\'s dom .
');
$.get("http://xyz.com/process.php?dataToProcess="+read,function(data){
alert(data);
});
But I see that the $.get("http://xyz.com/process.php?dataToProcess="+read,function(data){
// leads to a cross domain ajax request
I do not want to solve the cross domain ajax problem .
I want to be able to communicate between the two parties(the one with the embeddable script and my server) seamlessly .
If all you need to do is a GET request, you can use JSON-P(http://en.wikipedia.org/wiki/JSON#JSONP).
In your JavaScript, the syntax would be something like this:
$.getJSON("http://xyz.com/process.php?dataToProcess=" + encodeURIComponent(read) + "&callback=?",
function(result){
alert(result);
});
The "callback=?" property tells JQuery that this is a JSON-P request. JQuery will substitute some arbitrary string for the "?" (more details here: http://api.jquery.com/jQuery.getJSON/).
To make this work properly, you also need to change your process.php handler. The PHP handler should first read the value of the "callback" query parameter, and then wrap the response in that value.
For example, if $.getJSON() sends the parameter "callback=abcd" to the php page, the php page should return:
abcd({"data": "json object with the result"});
A few things to note:
Be sure to escape any user data you send to the server using encodeURIComponent();
If process.php modifies user data, you should be careful when using GET requests, as that could lead to XSRF attacks (http://en.wikipedia.org/wiki/Cross-site_request_forgery).
I used this the cross domain iframe hack to commmunicate between the two different domain . I recommend reading this
http://softwareas.com/cross-domain-communication-with-iframes

jsonp request not working in firefox

I am trying a straightforward remote json call with jquery. I am trying to use the reddit api. http://api.reddit.com. This returns a valid json object.
If I call a local file (which is what is returned from the website saved to my local disk) things work fine.
$(document).ready(function() {
$.getJSON("js/reddit.json", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
If I then try to convert it to a remote call:
$(document).ready(function() {
$.getJSON("http://api.reddit.com", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
it will work fine in Safari, but not Firefox. This is expect as Firefox doesnt do remote calls due to security or something. Fine.
In the jquery docs they say to do it like this (jsonp):
$(document).ready(function() {
$.getJSON("http://api.reddit.com?jsoncallback=?", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
however it now stops working on both safari and firefox. The request is made but what is return from the server appears to be ignored.
Is this a problem with the code I am writing or with something the server is returning? How can I diagnose this problem?
EDIT Changed the address to the real one.
JSONP is something that needs to be supported on the server. I can't find the documentation, but it appears that, if Reddit supports JSONP, it's not with the jsoncallback query variable.
What JSONP does, is wrap the JSON text with a JavaScript Function call, this allows the JSON text to be processed by any function you've already defined in your code. This function does need to be available from the Global scope, however. It appears that the JQuery getJSON method generates a function name for you, and assigns it to the jsoncallback query string variable.
The URL you are pointing to (www.redit.com...) is not returning JSON! Not sure where the JSON syndication from reddit comes but you might want to start with the example from the docs:
$(document).ready(function() {
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function (data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#redditbox");
if ( i == 4 ) return false;
});
});
});
(apologies for formatting)
EDIT Now I re read your post, I see you intended to go to api.reddit.com unfortunately you haven't got the right parameter name for the json callback parameter. You might need to further consult the reddit documentation to see if they support JSONP and what the name of the callback param should be.
I'm not sure about reddit.com, but for sites that don't support the JSONP idiom you can still create a proxy technique (on the backend) that would return the reddit JSON, and then you would just make an ajax request to that that.
So if you called http://mydomain.com/proxy.php?url=http://api.reddit.com:
<?php
$url = $_GET["url"];
print_r(file_get_contents($url));
?>
http://api.reddit.com/ returns JSON, but doesn't appear to be JSONP-friendly. You can verify this, if you have GET, via
% GET http://api.reddit.com/?callback=foo
which dumps a stream of JSON without the JSONP wrapper.
http://code.reddit.com/browser/r2/r2/controllers/api.py (line 84) shows the code looking for 'callback' (not 'jsoncallback'). That may be a good starting point for digging through Reddit's code to see what the trick is.

Categories