21

I need to build a project to get into a JS bootcamp I am applying for. They tell me I may only use vanilla JS, specifically that frameworks and Jquery are not permitted. Up to this point when I wanted to retrieve a JSON file from an api I would say

$.getJSON(url, functionToPassJsonFileTo)

for JSON calls and

$.getJSON(url + "&callback?", functionToPassJsonPFileTo) 

for JSONP calls. I just started programming this month so please bear in mind I don't know the difference between JSON or JSONP or how they relate to this thing called ajax. Please explain how I would get what the 2 lines above achieve in Vanilla Javascript. Thank you.

So to clarify,

function jsonp(uri){
    return new Promise(function(resolve, reject){
        var id = '_' + Math.round(10000 * Math.random())
        var callbackName = 'jsonp_callback_' + id
        window[callbackName] = function(data){
            delete window[callbackName]
            var ele = document.getElementById(id)
            ele.parentNode.removeChild(ele)
            resolve(data)
        }

        var src = uri + '&callback=' + callbackName
        var script = document.createElement('script')
        script.src = src
        script.id = id
        script.addEventListener('error', reject)
        (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
    })
}

would be the JSONP equivalent?

oski369
  • 239
  • 1
  • 2
  • 5

4 Answers4

38

Here is the Vanilla JS version for $.getJSON :

var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

Ref: http://youmightnotneedjquery.com/

For JSONP SO already has the answer here

With $.getJSON you can load JSON-encoded data from the server using a GET HTTP request.

Community
  • 1
  • 1
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
  • That's the `$.getJSON()` equivalent, if it's not clear. Getting JSONP is significantly different. – Pointy Feb 09 '16 at 14:34
  • 2
    That link is a very useful resource, here's a line by line comparison: http://youmightnotneedjquery.com/#json – NMunro Feb 09 '16 at 14:40
19

ES6 has Fetch API which provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

It is easier than XMLHttpRequest.

fetch(url) // Call the fetch function passing the url of the API as a parameter
  .then(res => res.json())
  .then(function (res) {
    console.log(res)
    // Your code for handling the data you get from the API
  })
  .catch(function() {
    // This is where you run code if the server returns any errors
  });
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
pmaddi
  • 449
  • 5
  • 18
  • How can I get the data object? oh I [see](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data), `fetch(url).then(function(response) { response.text().then(function(text) { poemDisplay.textContent = text; }); });` – Timo Jan 20 '21 at 19:11
7

Here is a vanilla JS version of Ajax

var $ajax = (function(){
    var that = {};
    that.send = function(url, options) {
        var on_success = options.onSuccess || function(){},
            on_error   = options.onError   || function(){},
            on_timeout = options.onTimeout || function(){},
            timeout    = options.timeout   || 10000; // ms

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                //console.log('responseText:' + xmlhttp.responseText);
                try {
                    var data = JSON.parse(xmlhttp.responseText);
                } catch(err) {
                    console.log(err.message + " in " + xmlhttp.responseText);
                    return;
                }
                on_success(data);
            }else{
                if(xmlhttp.readyState == 4){
                    on_error();
                }
            }
        };
        xmlhttp.timeout = timeout;
        xmlhttp.ontimeout = function () { 
            on_timeout();
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }
    return that;
})();

Example:

$ajax.send("someUrl.com", {
    onSuccess: function(data){
        console.log("success",data);
    },
    onError: function(){
        console.log("Error");
    },
    onTimeout: function(){
        console.log("Timeout");
    },
    timeout: 10000
});
a.bjorkmann
  • 89
  • 2
  • 9
1

I appreciate the vanilla js equivalent of a $.getJSON above but I come to exactly the same point. I actually was trying of getting rid of jquery which I do not master in any way . What I'm finally strugglin with in BOTH cases is the async nature of the JSON request.

What I'm trying to achieve is to extract a variable from the async call

function shorten(url){

var request = new XMLHttpRequest();
bitly="http://api.bitly.com/v3/shorten?&apiKey=mykey&login=mylogin&longURL=";
request.open('GET', bitly+url, true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
  var data = JSON.parse(request.responseText).data.url;
  alert ("1:"+data); //alerts fine from within 
  // return data is helpless
  } 
};

request.onerror = function() {
   // There was a connection error of some sort
   return url;
};

request.send();

}

now that the function is defined & works a treat

shorten("anyvalidURL"); // alerts fine from within "1: [bit.ly url]"

but how do I assign the data value (from async call) to be able to use it in my javascript after the function was called

like e.g

 document.write("My tiny is : "+data);
  • 1
    > but how do I assign the data value (from async call) - You will have to pass a callback function.. something like `function shorten(url, onSuccess) ` and then call the onSuccess with the result object.. i.e. `data` – Milli Nov 02 '17 at 08:55