0

Hello I need some help i am new learning so well the question might be a little silly but anyways I am tired of search everywhere and not able to find the answer I need.

So basically I have this json located at http://swapi.co/api/people/1/?format=json and I have this function in javascript:

function get_data_api()
{
 var data = anything_in_http://swapi.co/api/people/1/?format=json

 alert("name_of_json_from_url")
 }

So what I am trying to is to assign to that var data everything cotained in the json URL and then fetched to every tag and show them in an alert.

Hope it makes sense!

2 Answers2

1

This is a JavaScript implementation you don't need JQuery

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

getJSON('http://swapi.co/api/people/1/?format=json',
  function(err, data) {
    if (err != null) {
      alert('You have an error: ' + err);
    } else {
      console.log(data);
      alert('The name from the URL: ' + data.name);
    }
  });
Teocci
  • 7,189
  • 1
  • 50
  • 48
0

You can use jQuery http://api.jquery.com/jquery.getjson/

var jqxhr = $.getJSON( "http://swapi.co/api/people/1/?format=json", function() {
  console.log( "success" );
})
  .done(function(data) {
    console.log( data.name );
});

This is a possible duplicate of How to get JSON from URL in Javascript? which is the first result on google with keyword "javascript json from url" maybe you were using a wrong keywords for searching

Extra info: How to add jQuery to your page Add inside html head <head> </head> the jQuery js file

Method 1: Use CDN hosted js file

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Method 2: Download jquery.min.js then

<script src="/path/in/your/server/jquery.min.js"></script>
Community
  • 1
  • 1
Nawwar Elnarsh
  • 1,049
  • 16
  • 28
  • it is not clear unfortunatelly for me, I tried did copy paste in my function run it but it does not show anything in fact the console show only an error "Uncaught ReferenceError: $ is not defined" and here is the function function get_data_api() { var jqxhr = $.getJSON( "http://swapi.co/api/people/1/?format=json", function() { console.log( "success" ); }) .done(function(data) { console.log( data.name ); }); } – user6336440 Mar 27 '17 at 05:12
  • Modified answer to explain how to add jQuery – Nawwar Elnarsh Mar 27 '17 at 16:25