-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";
  });
}
1
  • Check out fetch() Commented Oct 15, 2018 at 23:56

2 Answers 2

1

You can use fetch api like so:

fetch(url).then(res => res.json()).then(data => {
  //whatever you want
})
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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 ();

1 Comment

Thank you for showing that I should use AJAX to do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.