Loading external JSON with Javascript - javascript

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.

Related

Combine two javascript calls into one involving a GET-request

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.

JS script calls a PHP script but then I can't handle the JSON for the html

I'm a beginner and I'm writing a js function that every 1 second it calls a PHP script where it checks some values on mysql DB, PHP encodes them in Json, then JS again decode it and throw them into html.
I have two questions for you:
-Why do you think this code is not properly working? It only writes the first value into the <p> list.
-How can I make this scalable? Every call to the php script executes a query. I need something like realtime, but I think using this way I'll destroy my server soon xD
JS
setInterval(function(){
$.getJSON("php/checkstatus.php", function(result){
$("#status").html(result['status']);
$("#tempint").html(result['tempint']);
$("#tempext").html(result['tempext'] + " ");
$("#humidityext").html(result['humidityext'] + " ");
});
},1000);
The json is like this:
{"status":"0","tempext":"25","tempint":"150","humidityext":"65"}
and the HTML is like this:
<p>status: <span id='status'>xx</span> .</p>
<p>Inside temperature: <span id='tempint'>xx</span> °C</p>
<p>Outside temperature: <span id='tempext'>xx</span> °C</p>
<p>Outside humidity: <span id='humidityext'>xx</span> </p>
Possibility is, there are multiple elements with same id in your HTML for tempint, tempext and humidityext.
To debug, open browser's console, then query all four elements like,
$("#status")
and similar with the remaining three, now you will get HTML tag as a result, hover over that tag and see if your desired tag to put data on highlights or not.
If you see any other than your desired tag to highlight, that means you have elements with duplicate IDs. You need to workaround for that.
For the second question, you can give http://socketo.me/demo a try.
The 'result' variable returned from your call is not an array but an object (json stands for JavaScript Object Notation). You can access them with a ".", like:
$("#status").html(result.status);
Can't help you with your second question.
The code above seems to be fine. I tested it on the local server and it works well.
Make sure to include a jquery library, for example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Furthermore, do you test it through a web server?
Check your console tab if you are using Google Crome and report any errors.
Try using the jQuery $.ajax function instead of $.getJSON. You have access to error handling if the request fails.
function GetData() {
$.ajax({
url: 'php/checkstatus.php',
dataType: 'json'
}).done(function(result) {
$("#status").html(result['status']);
$("#tempint").html(result['tempint']);
$("#tempext").html(result['tempext'] + " ");
$("#humidityext").html(result['humidityext'] + " ");
});
}
setInterval(function() { GetData(); }, 1000);
This was working for me in IE, Chrome and Firefox.
I tested with the following JSON file:
<?php
$tempext = rand(20, 100);
$tempint = rand(100, 200);
$humidityext = rand(30, 100);
echo '{"status":"0","tempext":"'.$tempext.'","tempint":"'.$tempint.'","humidityext":"'.$humidityext.'"}';
As for performance of your server, take a look at this post for an interesting option that describes how Facebook handled some of their traffic. How does facebook, gmail send the real time notification?

Trying to get JSONP but JS thinks that I'm pointing to other JS file

I'm trying to download JSONP from other server but I still getting error (in FF inspector SyntaxError: missing ; before statement).
To connect with server I'm using simple $.getJSON:
$.getJSON(url + "?callback=?", function(data) {
$("#main").html(data);
});
On the server I have this JSON:
{"branchName":"war140820rc1","commitId":"fcf600371bc9e837290799e0d7f7e848ccf12e7d"}
What is my problem? I checked this code multiple times and it looks like other JSONP downloaders.
Keep in mind that the request will look something like this:
<script src="http://yourdomain.com/?callback=callback"></script>
Which means it is handled as a Javascript file. Therefor you the callback passed in ?callback= should be called like every other javascript function, and you pass the result in json. Like:
callback(<?= MYJSON ?>);

Reading contents from a JSON url and writing out those contents

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
});

Receiving JSON from a website in JavaScript

So I have this website that has JSON object and trying to have it as an object.
As most people do once it comes to javascript problem, I took a look into jQuery and found out about awesome function called .getJSON(). (Example is below, and one can replace file name with URL)
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
Which is not that hard to figure out... But problem is, below statement.
Due to browser security restrictions, most "Ajax" requests are subject
to the same origin policy; the request can not successfully retrieve
data from a different domain, subdomain, or protocol.
Considering my page and the source page is not from same source, above method is not a possible option for me.
Is there any other way to solve this problem?
Thank you in advance.
From the docs:
If the URL includes the string "callback=?" (or similar, as defined by
the server-side API), the request is treated as JSONP instead.
So you need to change your url slightly to read like http://path/to/resource?callback=?
This only works if the resource supports JSONP, which means the server will wrap the data in a function call corresponding to your callback parameter, which jQuery will then reference in a script tag. If you can't use JSONP, your only option is some sort of server-side proxy.

Categories

Resources