40

I have an external resource similar to https://www.googleapis.com/freebase/v1/text/en/bob_dylan which returns a JSON. I want to display the value of result key in a div in html (lets say the name of the div is "summary"). Also the value of result key should be displayed in plain text.
The URL returns the json:

{ "result": "Bob Dylan, born Robert Allen Zimmerman, is an American singer-songwriter, author, poet, and painter, who has been a major figure in popular music for five decades. Much of Dylan's most celebrated work dates from the 1960s, when he became an ......." }

The JSON has just the result key, no other keys
Basically I do not want to use anything other than plain HTML and JavaScript. I am a relative beginner to JavaScript and therefore I ask for commented code.

Dr narendra thorat
  • 413
  • 1
  • 4
  • 5
  • This is a fairly basic HTML/AJAX problem. What code do you have so far? Where are you getting stuck? Here's the jQuery docs for AJAX specifically doing a `GET` for JSON data: http://api.jquery.com/jQuery.getJSON/ - The problem you'll likely run into is the same-origin policy since you'd be doing an AJAX request against a different domain than where your script is running. – Merlyn Morgan-Graham Mar 29 '12 at 09:12
  • There is a possibility of getting CORS error when we try to load JSON data from external resource using AJAX – Srini Karthikeyan Jun 30 '21 at 18:21

7 Answers7

33

Here is one without using JQuery with pure JavaScript. I used javascript promises and XMLHttpRequest You can try it here on this fiddle

HTML

<div id="result" style="color:red"></div>

JavaScript

var getJSON = function(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        resolve(xhr.response);
      } else {
        reject(status);
      }
    };
    xhr.send();
  });
};

getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan').then(function(data) {
    alert('Your Json result is:  ' + data.result); //you can comment this, i used it to debug

    result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
  alert('Something went wrong.');
});
b4hand
  • 9,550
  • 4
  • 44
  • 49
Rami Sarieddine
  • 5,396
  • 35
  • 41
  • 4
    Promise is not supported by older browsers. – D.A.H Feb 19 '15 at 14:17
  • In the newest version of Chrome, the first part of the "then" function works, I get results if the url is correct. If the url is incorrect, however, I never get the "Something went wrong" alert. Maybe it has something to do with how Fiddler works? – Bjarte Aune Olsen Sep 10 '15 at 20:00
  • Promises are not supported in *any* version of Internet Explorer http://caniuse.com/#feat=promises and you don't *need* Promises for a simple HTTP request... – nelsonic Feb 22 '16 at 16:42
  • 1
    true, but now Edge is the new browser that supports Promises. you might not need Promises but it is the new standard way of doing asynchronous JS so why not write neat script? – Rami Sarieddine Feb 23 '16 at 21:57
  • @Abderrahim sorry the page was not found. did you remove the question? – Rami Sarieddine May 25 '16 at 13:26
  • excellent solution and to the point. someone give Rami a cookie – Devashish May 18 '19 at 10:07
25

You can do this with JSONP like this:

function insertReply(content) {
    document.getElementById('output').innerHTML = content;
}

// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'http://url.to.json?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);

But source must be aware that you want it to call function passed as callback parameter to it.

With google API it would look like this:

function insertReply(content) {
    document.getElementById('output').innerHTML = content;
}

// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);

Check how data looks like when you pass callback to google api: https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply

Here is quite good explanation of JSONP: http://en.wikipedia.org/wiki/JSONP

Xavier
  • 274
  • 2
  • 3
10

Since it's an external resource you'd need to go with JSONP because of the Same origin policy.
To do that you need to add the querystring parameter callback:

$.getJSON("http://myjsonsource?callback=?", function(data) {
    // Get the element with id summary and set the inner text to the result.
    $('#summary').text(data.result);
});
Sani Huttunen
  • 23,620
  • 6
  • 72
  • 79
6

If you want to use plain javascript, but avoid promises, you can use Rami Sarieddine's solution, but substitute the promise with a callback function like this:

var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

And you would call it like this:

getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan', function(err, data) {
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {
    alert('Your Json result is:  ' + data.result);
    result.innerText = data.result;
  }
});
Robin Hartmann
  • 2,087
  • 1
  • 15
  • 26
  • 1
    I am getting a "No 'Access-Control-Allow-Origin' header" error in Chrome with this solution. Didn't work for me. – Jason Glisson Jan 05 '17 at 15:17
  • 1
    You're right. This only works if the server declares the 'Access-Control-Allow-Origin' header and allows others to access its resources. Otherwise, you'll have to use JSONP (if the server supports it) or a CORS proxy server, which downloads the data and sets the header for you. – Robin Hartmann Jan 05 '17 at 17:02
1

You can use $.ajax call to get the value and then put it in the div you want to. One thing you must know is you cannot receive JSON Data. You have to use JSONP.

Code would be like this:

function CallURL()  {
    $.ajax({
        url: 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan',
        type: "GET",
        dataType: "jsonp",
        async: false,
        success: function(msg)  {
            JsonpCallback(msg);
        },
        error: function()  {
            ErrorFunction();
        }
    });
}

function JsonpCallback(json)  {
    document.getElementById('summary').innerHTML = json.result;
}
Vedaant Arya
  • 475
  • 6
  • 18
Shahriar
  • 75
  • 2
0

To display the Json data using Robin Hartman code. You need to add, the below line.

The code he gave gives you Object, object. this code retrieves the data in a better way.

result.innerText =JSON.stringify(data);
  • He says, " I want to display the value of result key in a div in html" and that's exactly what my and Rami Sarieddine's code does. Your code would display the entire data, which is not what he wants. – Robin Hartmann Mar 28 '17 at 14:27
-1

Since the desired page will be called from a different domain you need to return jsonp instead of a json.

$.get("http://theSource", {callback : "?" }, "jsonp",  function(data) {
    $('#summary').text(data.result);
});
Marius Schulz
  • 15,976
  • 12
  • 63
  • 97
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192