Books on ajax and using api

Hello friends,
I am trying to make the build the random quote machine. I have figured out I am quite unclear in ajax and using api. I am trying hard . Need some suggestions for a good book on ajax concepts and using api with ajax and json.

You may refer Tutorialspoint (Jquery) or just use Mozilla MDN Pages . But i suggest you to look into official documents at https://jquery.com/ website.

1 Like

AJAX can be really difficult to grasp until you start having some success with using it, because often we, as front-end devs, run into Cross Origin Resource Sharing (CORS) problems - a topic you should explore more on your own.

I recommend an API that doesn’t require registration, has no usage limits, and doesn’t require JSONP. There are two random quote API services that fit this criteria (that I’m aware of - there are likely more):

  1. Quotes on Design - http://quotesondesign.com/api-v4-0/

While their example uses JSONP, requests can be made for regular JSON. Modifying their example request, here is what I recommend:

$.ajax({
  cache: false,
  jsonp: false,
  url: "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1",
  success: function(data) {
    // study how the returned data is structured
    console.dir(data);
  }
});

It’s important to note that the request is for an http resource. You might run into issues if your domain is https when making this request. The cache property in the ajax request is to prevent caching the first ajax response. To learn why I added jsonp: false I encourage you to read the docs: https://api.jquery.com/jquery.ajax/

In short, JSONP is a potential security issue. Try to avoid using JSONP if you can.

  1. The Internet Chuck Norris Database - http://www.icndb.com/api/

Similar to using Quotes on Design, the request url is using the http protocol, however, with this API we don’t need to explicitly prevent caching - we’ll always get a random quote without having to set this property.

$.ajax({
  jsonp: false,
  url: "http://api.icndb.com/jokes/random",
  success: function(data) {
    console.dir(data);
  }
});

There’s a lot more to this project than making a successful AJAX request, however, this can be the most tricky part to understand when trying to deal with CORS, whether or not JSONP is required, and loading HTTP over HTTPS - it’s a lot of new stuff thrown at us without much warning or preparation.

Finally, as a nugget you can choose to explore or not, JavaScript has native AJAX via the fetch() function. Probably not something to try and use right now (it uses ES6 Promises), but be aware that it’s available when you get more comfortable with jQuery’s AJAX.

4 Likes

Thankyou. I am new into coding and your advice has helped me in a good direction. I am going to review the concepts in detail before going forward with this project.