Calling Rest API from JavaScript / jQuery

Calling Rest API from JavaScript / jQuery

How to call rest APIs in javascript/jquery. In this tutorial, you will learn how to call rest APIs in javascript/jquery on your web applications or web pages.

How to call rest APIs in javascript/jquery. In this tutorial, you will learn how to call rest APIs in javascript/jquery on your web applications or web pages.

If you are looking for how to consume restful web services in javascript, call rest service from HTML page, jquery rest API post, ajax API, call example, jquery API call, calling web API from jquery ajax, javascript call rest API JSON. This tutorial solves your all queries related to calling APIs (web services).

In this web services (Apis) tutorial, we will call Google’s free news web service (API). This will make it easier for you to learn how to call web service and API in JavaScript and Jquery using Ajax.

You might not know that Google provides free (web services) APIs for news. You can get the Google News API key by clicking on the link given below. https://newsapi.org/docs/get-started

Calling Google News RESTful Web Service with JavaScript / jQuery

This guide walks you through writing a simple javascript/jquery to calling rest web service.

Google News Apis key:

e03753c9126b408d870a44318813ac3d

This the google news web services (Apis)

https://newsapi.org/v2/top-headlines?country=us&apiKey=e03753c9126b408d870a44318813ac3d

When we call Google News API and web service with the help of javascript and jquery then we will get the JSON response given below.

[
{
"status": "ok",
"totalResults": 38,
"articles": [
    {
    "source": {
    "id": null,
    "name": "Youtube.com"
    },
    "author": null,
    "title": "Coronavirus: Death toll rises to 81 as China extends holiday  BBC News  BBC News",
    "description": "The number of people killed in China by the new coronavirus has risen to 81, with almost 3,000 confirmed ill. The national new year holiday has been extended...",
    "url": "https://www.youtube.com/watch?v=S2VoEvDEuxw",
    "urlToImage": "https://i.ytimg.com/vi/S2VoEvDEuxw/maxresdefault.jpg",
    "publishedAt": "20200127T10:35:49Z",
    "content": "The number of people killed in China by the new coronavirus has risen to 81, with almost 3,000 confirmed ill.
    The national new year holiday has been extended by three days to Sunday, in an attempt to contain the spread.
    On Monday, Chinese Premier Li Keqiang… [+268 chars]"
    },
 
    {
    "source": {
    "id": "thewashingtonpost",
    "name": "The Washington Post"
    },
    "author": "Gerry Shih, Simon Denyer",
    "title": "Worries grow that quarantine in China not enough to stem increasingly virulent coronavirus  The Washington Post",
    "description": "Even as the quarantine was being laid down, some 5 million people left Wuhan, the virus epicenter.",
    "url": "https://www.washingtonpost.com/world/coronaviruschinalatestupdates/2020/01/27/3634db9a40a711eaaa6a083d01b3ed18_story.html",
    "urlToImage": "https://www.washingtonpost.com/resizer/AaxiGLihZ1dJXlirb6FyJqaARSY=/1440x0/smart/arcanglerfishwashpostprodwashpost.s3.amazonaws.com/public/4O4ONFSA4YI6VKTKBA6QDM7NDA.jpg",
    "publishedAt": "20200127T10:21:00Z",
    "content": "Chinas health minister said the coronavirus is increasing in virulence and now could be contagious even before people exhibit symptoms making perfectly healthyseeming people possible carriers.
     A scientific assessment of the disease spread assuming an optim… [+10160 chars]"
    }
   ]
  }
]

Create a js File

First, you will create the js file and in this file call the web service (apis) :
public/my-news.js

$(document).ready(function() {
    $.ajax({
        url: "https://newsapi.org/v2/top-headlines?country=us&apiKey=e03753c9126b408d870a44318813ac3d"
    }).then(function(data) {
        
        for (i = 0; i < data.articles.length; i++) {
          $('#news').append("<ul><li>"+data.articles[i].title+"</li></ul>");
        }
        
    });
});

This controller module is represented as a simple JavaScript function. It uses jQuery’s $.ajax() method to consume the REST service at https://newsapi.org/v2/top-headlines?country=us&apiKey=e03753c9126b408d870a44318813ac3d. If successful, it will assign the JSON received to data, effectively making it a Greeting model object. The id and content are then appended to the news id and DOM elements respectively.

Note the use of the jQuery promise .then(). This directs jQuery to execute the anonymous function when the $.ajax() method completes, passing the data result from the completed AJAX request.

Create the Web Page

Now that you have a js, you will create the HTML page that will load the google news into the user’s web browser:

public/index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Google News Apis</title>
        <script src="https://code.jquery.com/jquery-3.4.1.js"></script>  
        <script src="my-news.js"></script>
    </head>
 
    <body>
        <div id="news"> </div>
    </body>
</html>

We need to add two jQuery /JavaScript libraries inside the head tag on html web page. The former gives jQuery. He: We have created another in which we will call Web Services / Interconnect

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>  
<script src="my-news.js"></script>

We have created a div in an html web page. When calling Google’s free news API / web service, the format that will get the response, we will read in this div. Of the jquery append method ():

Call the API

Open your browser and simply hit the following url into your browser:

file:///C:/Users/Desktop/public/index.html

Understand and Use JavaScript's .forEach() vs. jQuery's .each()

Understand and Use JavaScript's .forEach() vs. jQuery's .each()

There are two functions to deal with an array on the client-side – JavaScript's .forEach() and jQuery's .each(). Here, I will teach you how to use both of these methods with some sample code.

Your knowledge of JavaScript and jQuery is incomplete if you don't know how to loop with .forEach() and .each() methods. This tutorial helps you to quickly master JavaScript .forEach() & jQuery .each() in 2 minute time.

There are two methods to deal with an array on client-side – JavaScript .forEach() and jQuery .each(). Here, I will teach you how to use both of these methods in different scenarios.

Defination of these 2 methods

a. JavaScript .forEach() Method

The .forEach() method of JavaScript executes a given function once for each element of the array.

For example -

var arr = ['a', 'b', 'c'];    
arr.forEach(function(element) {  
    console.log(element);  
});  

The above JavaScript code will print – ‘a’, ‘b’, & ‘c’ in the console window.

b. jQuery .each() Method

jQuery has it’s own method called jQuery Each method and it is used to loop over arrays, array of object and matched elements of the DOM. See the below code:

var arr = ['a', 'b', 'c'];  
$.each(arr , function (index, value){  
  console.log(arr);   
});  

The above jQuery code will print – ‘a’, ‘b’, & ‘c’ in the console window.

Looping through DOM elements

a. JavaScript .forEach() Method

Suppose you want to extract all the anchor tags from the web page, and then loop through each of them. In that case first you have to get all the anchors using document.getElementsByTagName("a") and then convert it into an array. This is because JavaScript .forEach() method loops only through an array.

See the below code:

var links = document.getElementsByTagName("a");    
var Arr = Array.from(links);    
Arr.forEach(someFunction);    
    
function someFunction(currentValue) {    
    console.log(currentValue);    
}    

I used Array.from() method to convert to an array.

b. jQuery .each() Method

In case of .each() method you simply loop through all the anchor tags, like shown in the below code, as jQuery Each method can loop through arrays, array of objects and matched element of the DOM. So you don’t have to do the conversion to an array like JavaScript .forEach() method.

See the below code:

$("a").each(function (index, value) {   
  console.log($(this).attr("href"));   
});  

Clearly you can see in this case the lines of codes are very less than compared to .forEach() method of JavaScript.

Which one you should choose?

Case 1: DOM Manipulations

When working with DOM elements the jQuery Each method has a great advantage because it removes a lot of code lines. So prefer this method during DOM manipulations.

Case 2: Website is using jQuery from before

If your website is already using jQuery then you should use jQuery Each method because this will bring code consistency in your project.

In all other cases use JavaScript .forEach() method.

Conclusion

Both of these above methods are very good and they make the codes easy to understand. I would recommend every web developer to know both of these methods.

Thank you for reading.

jQuery vs Vanilla JavaScript - Beau teaches JavaScript

jQuery vs Vanilla JavaScript - Beau teaches JavaScript

When should you use jQuery instead of vanilla JavaScript? Is jQuery still relevant? What is jQuery good for? jQuery vs vanilla JavaScript - Beau teaches JavaScript

When should you use jQuery instead of vanilla JavaScript? Is jQuery still relevant? What is jQuery good for? Find out in this video!

3 JavaScript libraries to replace jQuery

3 JavaScript libraries to replace jQuery

Ubiquitous jQuery has been outmoded by JavaScript and browser advances. Cash, Zepto, and Syncfusion are three JavaScript libraries picking up where jQuery left off

Simplifying tasks such as HTML document traversal, animation, and event handling, the stalwart jQuery JavaScript library changed the face of web development. As of May 2019, **jQuery **is still being used in 74 percent of known websites, according to web technology surveyor W3Techs. Nevertheless, the jQuery library, which debuted in August 2006, is now being viewed by some developers as an older technology whose time has passed.

Alternatives to **jQuery **have emerged in recent years, such as the Cash library or even just modern, vanilla JavaScript, now that web browsers all handle **JavaScript libraries **the same way and jQuery is no longer needed to solve compatibility issues. Arguments on Reddit and videos on YouTube make the case that jQuery has become obsolete, or at least is not as essential as it once was.

Why jQuery is no longer needed

In one YouTube presentation, “Is jQuery still relevant in 2018?,” web development educator Brad Traversy acknowledges that jQuery is probably the best generalized JavaScript library ever created. It is easy to learn, cross-browser compatible, more concise than older vanilla JavaScript, and rich in plug-ins offering specific functionality. But JavaScript has advanced far since ECMAScript 6, and jQuery is no longer needed in many situations, Traversy concludes.

In another video, coding educator Kenneth Lowrey argues that becoming fluent in jQuery is a waste of time. In the current web development landscape, modern browsers handle JavaScript the same, for the most part. In most cases, native JavaScript code is better than a “bloated legacy library like jQuery,” he says.

While jQuery had been the choice for making HTTP requests, for example, ECMAScript 6 brought forth Fetch, a promised-based API that makes HTTP requests easier. And the advancement does not stop with HTTP. Where jQuery has utilities for tasks such as manipulating arrays, vanilla JavaScript now has improved accommodations for these operations, too.

Animations are still more difficult with vanilla JavaScript than jQuery, but there are other options such as CSS transitions or keyframes, Traversy points out. The third-party GreenSock library also can be used for animations. For DOM manipulation, a task once ruled by jQuery, native browser APIs have closed the gap.

For tasks that cannot be done in vanilla JavaScript, Traversy recommends specialized libraries, instead of a generalized library like jQuery. Traversy also recommends using JavaScript frameworks such as React, Angular, or Vue for mid-size and large applications. Traversy still recommends jQuery for use on simple sites with no framework.

jQuery alternatives

What should you use instead of jQuery? Besides modern, vanilla JavaScript, a short list of jQuery alternatives includes Cash, Zepto, and Syncfusion Essential JS 2. Cash and Zepto are open source JavaScript libraries available under an MIT license. Syncfusion Essential JS 2 is a commercial product.

Cash

Cash has more than 3,570 stars on GitHub. Billed as an “absurdly small jQuery alternative” for modern browsers, Cash has a jQuery-style syntax for manipulating the DOM and takes up 32KB of space, uncompressed. Cash supports capabilities including namespaced events, TypeScript types, and modern builds. You can download Cash from GitHub.

Zepto

Zepto is described as “a minimalist **JavaScript library **with a largely jQuery-compatible API.” Developers who know jQuery already know how to use Zepto, its makers go on to say. Zepto purports to be much smaller and faster-loading than jQuery, and can work with the PhoneGap toolset for mobile and desktop browsers. You can download Zepto from the project website.

Syncfusion Essential JS 2

Syncfusion Essential JS 2 is a commercially licensed JavaScript UI controls library written in TypeScript. Serving as an alternative to the jQuery UI library, Syncfusion is designed to be a low-overhead, lightweight, and modular library to improve web applications. Syncfusion supports frameworks including Angular, React, and Vue. You can purchase Syncfusion Essential JS 2 or download a free trial from the Syncfusion website. Complete source code, unit test files, test scripts, and live demos are available on GitHub.