Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add the XHR request to request image and article #1

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions lesson-1-async-w-xhr/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,66 @@
e.preventDefault();
responseContainer.innerHTML = '';
searchedForText = searchField.value;


//const searchedForText = searchField.value;
//console.log(searchedForText);
const unsplashRequest = new XMLHttpRequest();
unsplashRequest.open('GET', `https://api.unsplash.com/search/photos?page=1&query=${searchedForText}`);
unsplashRequest.onload= addImage;
unsplashRequest.setRequestHeader('Authorization', 'Client-ID nRQgo4D9Ip9s2k8YmeR39hV2B6-G9kzjyki9NQfvIrg')
unsplashRequest.send()

// this function will add image fetched from Asynchronus Http Request to the page withot the need to reload the page
function addImage(){
// debugger;
let htmlContenet ='';
//convert rsposnse to java script
const data = JSON.parse(this.responseText);
//check if there is a response image or not
if (data && data.results && data.results[0]){
const firstImage = data.results[0];
htmlContenet = `<figure>
<img src="${firstImage.urls.regular}" alt="${searchedForText}">
<figcaption>${searchedForText} by ${firstImage.user.name}</figcaption>
</figure>`;
}else{
htmlContenet = `<div class="error-no-image"> No images available</div>`;
}
//update page with returned imag from API Uspalsh
responseContainer.insertAdjacentHTML('afterbegin', htmlContenet);
}


// then make another XHR request to get the articles from NYTimes newspaper related to search
const articleRequest = new XMLHttpRequest();
// when the request retrun it calls the addArticle function
articleRequest.onload = addArticles;
//https://api.nytimes.com/svc/search/v2/articlesearch.json?q=us&api-key=W1fdekfDs1A43nsSvHyyZUK368U2TjKQ
console.log(searchedForText);
articleRequest.open('GET', `https://api.nytimes.com/svc/search/v2/articlesearch.json?q=${searchedForText}&api-key=W1fdekfDs1A43nsSvHyyZUK368U2TjKQ`);
articleRequest.send();
// this function will add the article fitched from NewYourkTimes related to the search field
function addArticles () {
let htmlContenet ='';
//convert rsposnse to java script
const data = JSON.parse(this.responseText);
// check if there is a response article
if (data.response && data.response.docs && data.response.docs.length > 1){
// place result articles in an unordered list
htmlContenet ='<ul>' + data.response.docs.map(article => `<li class="articles">
<h2><a href="${article.web_url}">${article.headline.main}</a></h2>
<p>${article.snippet}</p>
</li>`).join('' + '</ul');
}else {
htmlContenet = '<div class="error-no-article">Nor Articles Available</div>';
}

responseContainer.insertAdjacentHTML('beforeend',htmlContenet);



}

});
})();
56 changes: 56 additions & 0 deletions lesson-2-async-w-jQuery/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,61 @@
e.preventDefault();
responseContainer.innerHTML = '';
searchedForText = searchField.value;

// use Ajax instead of XHR to handle API request
$.ajax({
url:`https://api.unsplash.com/search/photos?page=1&query=${searchedForText}`,
headers: {Authorization: 'Client-ID nRQgo4D9Ip9s2k8YmeR39hV2B6-G9kzjyki9NQfvIrg'}
}).done(addImage);

// this function will add image fetched from Asynchronus Http Request to the page withot the need to reload the page
function addImage(images){
// debugger;
console.log(images);
let htmlContenet ='';
//no need to convert rsposnse to java script as ajaax do this
//const data = JSON.parse(this.responseText);
//check if there is a response image or not

if (images && images.results && images.results[0]){
const firstImage = images.results[0];
htmlContenet = `<figure>
<img src="${firstImage.urls.small}" alt="${searchedForText}">
<figcaption>${searchedForText} by ${firstImage.user.name}</figcaption>
</figure>`;
}else{
htmlContenet = `<div class="error-no-image"> No images available</div>`;
}
//update page with returned imag from API Uspalsh
responseContainer.insertAdjacentHTML('afterbegin', htmlContenet);
}

// Use Ajax to handle api request from NYtimes
$.ajax({
url:`https://api.nytimes.com/svc/search/v2/articlesearch.json?q=${searchedForText}&api-key=W1fdekfDs1A43nsSvHyyZUK368U2TjKQ`,
}).done(addArticles);

function addArticles (articles) {
console.log(articles);
let htmlContenet ='';
//convert rsposnse to java script
//const data = JSON.parse(this.responseText);
// check if there is a response article
if (articles.response && articles.response.docs && articles.response.docs.length > 1){
// place result articles in an unordered list
htmlContenet ='<ul>' + articles.response.docs.map(article => `<li class="articles">
<h2><a href="${article.web_url}">${article.headline.main}</a></h2>
<p>${article.snippet}</p>
</li>`).join('' + '</ul');
}else {
htmlContenet = '<div class="error-no-article">Nor Articles Available</div>';
}

responseContainer.insertAdjacentHTML('beforeend',htmlContenet);



}

});
})();
2 changes: 2 additions & 0 deletions lesson-2-async-w-jQuery/jquery-3.6.0.min.js

Large diffs are not rendered by default.

62 changes: 62 additions & 0 deletions lesson-3-async-w-fetch/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,67 @@
e.preventDefault();
responseContainer.innerHTML = '';
searchedForText = searchField.value;

fetch(`https://api.unsplash.com/search/photos?page=1&query=${searchedForText}`, {
headers: {
Authorization: 'Client-ID nRQgo4D9Ip9s2k8YmeR39hV2B6-G9kzjyki9NQfvIrg'
}
}).then(response=> response.json())
.then(addImage)
//Again, because a Fetch request returns a Promise .catch() is available to us from the Promise API.
//So let's add a .catch() method to handle errors:
.catch(e => requestError(e, 'image'));

function addImage(data) {
let htmlContent = '';
const firstImage = data.results[0];
if (firstImage) {
htmlContent = `<figure>
<img src="${firstImage.urls.small}" alt="${searchedForText}">
<figcaption>${searchedForText} by ${firstImage.user.name}</figcaption>
</figure>`;
} else {
htmlContent = 'Unfortunately, no image was returned for your search.'
}
responseContainer.insertAdjacentHTML('afterbegin', htmlContent);
}
// this function treated the error if no image orr network erro
function requestError(e, part) {
console.log(e);
responseContainer.insertAdjacentHTML('beforeend', `<p class="network-warning">Oh no! There was an error making a request for the ${part}.</p>`);
}

// fetch the articles from NewYork times
fetch (`https://api.nytimes.com/svc/search/v2/articlesearch.json?q=${searchedForText}&api-key=W1fdekfDs1A43nsSvHyyZUK368U2TjKQ`)
.then(response=> response.json())
.then(addArticles)
.catch(e => requestError(e, 'articles'));

function addArticles (articles) {
console.log(articles);
let htmlContenet ='';
//convert rsposnse to java script
//const data = JSON.parse(this.responseText);
// check if there is a response article
if (articles.response && articles.response.docs && articles.response.docs.length > 1){
// place result articles in an unordered list
htmlContenet ='<ul>' + articles.response.docs.map(article => `<li class="articles">
<h2><a href="${article.web_url}">${article.headline.main}</a></h2>
<p>${article.snippet}</p>
</li>`).join('' + '</ul');
}else {
htmlContenet = '<div class="error-no-article">Nor Articles Available</div>';
}

responseContainer.insertAdjacentHTML('beforeend',htmlContenet);



}





});
})();