-2

Here is what I'm trying to figure out. How to write $.get(url,function(data) { code }; in pure JavaScript.

function newimage(keyword){
  if(!ACCESS_KEY){
    alert("Please update your access key");
    return;
  }
  var url = `https://api.unsplash.com/search/photos?query=${keyword}&per_page=20&orientation=landscape&client_id=${ACCESS_KEY}`;
  $.get(url,function(data){
    var picture = data.results[0];
    var picture_url = picture.urls.raw;
    var photo_by_name = picture.user.name;
    var photo_by_url = picture.user.links.html;
    setCookie("picture",picture_url,0.5);
    setCookie("photo-by-name",photo_by_name,0.5);
    setCookie("photo-by-url",photo_by_url,0.5);
    picInterest.innterHTML = `${keyword}`;
    photoBy.innterHTML = `${photoByUrl}`;
    photoBy.setAttribute('html', photoByUrl);
    document.querySelector("body").style.backgroundImage = `url(${pictureUrl})`;
    pictureOption.style.display = "block";
  });
}
Phil
  • 157,677
  • 23
  • 242
  • 245

2 Answers2

1

You can use fetch api like so:

fetch(url).then(res => res.json()).then(data => {
  //whatever you want
})
Phil
  • 157,677
  • 23
  • 242
  • 245
Natan Farkash
  • 256
  • 3
  • 4
  • 1
    Thank you. I am new to coding and have not learned all the different syntax for javascript. So, I was unaware of a different way to approach this. But thank you for pointing it out. – JasonSikes Oct 16 '18 at 00:18
0

You could use this:

var url = `https://api.unsplash.com/search/photos?query=${keyword}&per_page=20&orientation=landscape&client_id=${ACCESS_KEY}`;
var xhr = new XMLHttpRequest ();
xhr.open ( "GET", url);
xhr.onreadystatechange = function ()
{
  if ( xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200)
  {
    // Here you handle the response
    // Result text will be accessible at xhr.responseText
  }
}
xhr.send ();
Ernani Azevedo
  • 461
  • 2
  • 6