I need to make a GET request to retrieve a string and then pass that string onto another external javascript file. How can I combine an external Javascript file with a GET request?
In the problem below, I retrieve a value for the "token" variable and then want to pass it on to the second tag to use it in the "data-token" part.
Is there a way to combine these two actions into one tag? The way I am doing it now does not work and I have a hard time finding a solution. Probably due to my inexperience with javascript and not knowing the right terminology.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$.getJSON('https://demo4661814.mockable.io/monkey', function(data) {
token = data['msg'] // token = "txn_c3983f0bce163a0eb2b427c7a977eecd"
});
</script>
<script src="https://js.mockio.com/scripts/mockio.js"
data-token=token
data-additional="name,address,phone">
</script>
You can write the later tag in to the document when you get the result from the get script
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$.getJSON('https://demo4661814.mockable.io/monkey', function(data) {
token = data['msg'] // token = "txn_c3983f0bce163a0eb2b427c7a977eecd"
document.write('<script src="https://js.mockio.com/scripts/mockio.js" data-token=' + token + ' data-additional="name,address,phone"></script>');
});
</script>
You can create the script tag dynamically after retrieving the token:
$.getJSON('https://demo4661814.mockable.io/monkey', function(data) {
var token = data['msg']; // token = "txn_c3983f0bce163a0eb2b427c7a977eecd"
$('<script>')
.attr('src', 'https://js.mockio.com/scripts/mockio.js')
.attr('data-token', token)
.attr('data-additional', 'name,address,phone')
.appendTo('body');
});
You can create a single API which would serve both your requests.
By which I mean,
Create an API endpoint for example say it is, https://js.mockio.com/intermediateAPI. This API would internally request for https://demo4661814.mockable.io/monkey and would get the token. Once this request is successful and the response is received, the API would request for https://js.mockio.com/scripts/mockio.js with the token received from the above request and would serve the response to the user.
Related
The following script queries information from an API and outputs it into the HTML, using simple AJAX and Javascript.
The TOKEN for the API is exposed in the Javascript. In my opinion this is not safe because anybody who can access the page can see the token. IF this method is not safe, is there some additional method to hide the token? Ideally I would like to use Javascript, HTML, and PHP if needed. The existing script is very simple and so I'm wondering if there is a relatively simple way to protect the token.. rather than having to add a lot of additional new code or methods.
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.eventbriteapi.com/v3/events/eventid/?
token=TOKEN",
"method": "GET",
"headers": {}
}
$.ajax(settings).done(function (data) {
console.log(data);
var content = "<h2>" + data.name.text + "</h2>" + data.description.html +
data.start.utc;
$("#eventbrite").append(content);
});
</script>
<div id="eventbrite"></div>
</body>
</html>
You can make a simple proxy script on your server using PHP!
Your JavaScript will then call this script, including the event ID and nothing else in the GET parameter, so calling your PHP Proxy would be something like /proxy.php?eventid=123
To further fancify this example you could utilize $_SESSION etc to make sure your user has visiter the page before visit and only allow 1 request per pageload or something similar.
I have prepared a sample, but you have to modify it to fit your needs!
<?php
//Get event ID you want to request:
$eventID = isset($_GET['eventid']) ? $_GET['eventid'] : FALSE;
//Exit if no ID provided:
if (!$eventID) {
exit('No ID Provided.');
}
//Set your token:
$token = '<YOUR_TOKEN_HERE>';
//Set url, %s will be replaced later:
$url = 'https://www.eventbriteapi.com/v3/events/%s/?token=%s';
//Set url, pass in params:
$request_uri = sprintf($url, $eventID, $token);
//Try to fetch:
$response = file_get_contents($request_uri);
//Set content-type to application/json for the client to expect a JSON response:
header('Content-type: application/json');
//Output the response and kill the scipt:
exit($response);
Resources:
What is a Proxy (Wikipedia)
Update:
JavaScript:
$.getJSON('/proxy.php', {eventid: '<id_here>'}, function(response){
console.log(response);
var content = "<h2>" + data.name.text + "</h2>" + data.description.html +
data.start.utc;
$("#eventbrite").append(content);
});
You probably should not store the API key client-side, why not store it in the PHP scripts that the JS calls to?
If you really insist on storing it client-side you'll definitely want to encrypt it but I wouldn't want to rely on that.
Store your API key one the sever and make requests to it when you need it. To make it even more secure on your server side only return the API key if a token (which you've set) is passed and validated to prevent spoof AJAX requests.
For example:
PHP
/** Change $_POST respectively to what you need. **/
if (isset($_POST['request_api_key_token']) && $_POST['request_api_key_token'] == 'your_value') {
/** Return your API key. **/
} else {
exit(header('HTTP/1.0 403 Forbidden'));
}
I'm trying to catch some JSON info from a site.
My first exemple its just a test and work:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$.get("http://www.w3schools.com/jquery/demo_test.asp",function(data,status){
document.write("Data: " + data + "\n<br>Status: " + status);
});
});
</script>
But the problem its in my second example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$.get("https://btc-e.com/api/2/ltc_usd/ticker",function(data,status){
document.write("Data: " + data + "\n<br>Status: " + status);
});
});
</script>
PS - i'm trying to get the info from the page to use it in a blog :)
External JSON with jQuery means using JSONP. This works by the page returning a Javascript script instead, which calls a function (which you define) with the data you need. You can't get the data as normal JSON. So the response needs to look like this:
json_callback({"ticker":{"high":0.77,"low":0.64,"avg":0.705,"vol":107049.5563,"vol_cur":151754.22482,"last":0.76,"buy":0.766,"sell":0.75811,"server_time":1364653244}});
rather than
{"ticker":{"high":0.77,"low":0.64,"avg":0.705,"vol":107049.5563,"vol_cur":151754.22482,"last":0.76,"buy":0.766,"sell":0.75811,"server_time":1364653244}}
(The function would not be called json_callback, but would have a unique name each time.)
This obviously relies on the server's assistance, so the server needs to be set up to support JSONP. The normal way of indicating this is by adding callback=? to the end of the URL, where ? is the name of the function you want to call. If we try this, you'll see that the script does not change. This indicates that the website does not support JSONP requests, so there is no way of accessing this data using JSONP.
There are various other methods of getting the data. The simplest is probably proxying the data from the external server with your own server.
I have a url [https://www.inquicker.com/facility/americas-family-doctors.json] that is a JSON data url. How can I access the contents of this url, and write out the values.
The format contains schedules as an array that inside it contains schedule_id, name, and available_times. I have tried various ways of getting the JSON file, but none have worked.
UPDATE:
Well I have got it this far with this code, and it's laying out what looks like objects from the array. So I believe I got the cross site issue under control. I just need to figure out how to access the data now.
<!DOCTYPE html>
<html>
<head>
<title>JQuery (cross-domain) JSONP</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.getJSON('https://www.inquicker.com/facility/americas-family-doctors.json',
function(data){
alert(data.facility);
$.each(data.schedules, function(i, name){
$('#names').append('<li>' + name.available_times[0] + '</li>');
});
});
});
</script>
</head>
<body>
<ul id="names"></ul>
</body>
</html>
Any help, or suggestions will be greatly appreciated, Thanks.
You cannot generally pass an Ajax request across domains. Normally a server will refuse any Ajax calls that don't come from the same source unless it is explicitly configured otherwise. I am guessing that you aren't calling from the same domain, given that you are using a fully-qualified URL. If you own the server, you will have to configure it to accept such calls from your other domain.
If this is not the case, launch the script in Firefox with Firebug running and look at the console output and tell me what error you get if any.
Once you manage to pass the JSON from your server back to the page, you will retrieve it in your JavaScript as a string. You then need to execute this function:
var jsonObject = JSON.parse(jsonString);
where jsonString is the string that you received from your server. jsonObject becomes an object representation of the JSON passed back to the answer that you can access using dot notation.
Try something like :
alert(json.facility);
There is no title json object in the url you have mentioned.
The JSON is already parsed when it comes to your function.
$.get('https://www.inquicker.com/facility/americas-family-doctors.json', function(result){
alert(result.facility); //Do whatever you want here
// result.schedules array is also ready
});
I want to get the username's profile image. So i prefer to use twitter api version 1 for this.(The regular version of api is here). But my code doesn't return any data. How can i fix this?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).ready( function() {
var userPage = "https//twitter.com/jack";
var arr = userPage.split("/");
var username = "";
for(i=3;i<4;i++)
username += arr[i];
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username;
$.getJSON(page, function(data) {
alert(data.profile_image_url);
});
})
</script>
</head>
<body>
</body>
</html>
Add "&callback=?" to the URL to force jsonp format to get around the Access-Control-Allow-Origin issue.
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username + "&callback=?";
EXAMPLE
JSONP:
The way JSONP works is simple, but requires a little bit of
server-side cooperation. Basically, the idea is that you let the
client decide on a small chunk of arbitrary text to prepend to the
JSON document, and you wrap it in parentheses to create a valid
JavaScript document (and possibly a valid function call).
The client decides on the arbitrary prepended text by using a query
argument named jsonp with the text to prepend. Simple! With an empty
jsonp argument, the result document is simply JSON wrapped in
parentheses.
I am using following code in my html file and run manually not in webserver through double clicking only.it did not parse xml and give correct node value? any help please? how jquery
will work if xml content is big one, because the code i have used is not having callback function, how does it identify all xml data has been recieved before parsing?
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.get("http://www.hindu.com/rss/01hdline.xml", function(response){
var response = $.paseXML(response);
var $xml = $(response);
//Now you can find any xml node with $xml using various methods of jQuery
//E.g
alert($xml.find( "title" ));
});
});
your success handler will not be called, place an alert of see in firebug, because of "Same Origion Policy". Also have a look at Cross-Origin Resource Sharing
what you can do is make a server side proxy, make request to the Url and get a xml response, then pass back that response to your client side where you can use jquery to parse the xml.