Get data with the $.ajax() method

Published on: August 19, 2018

Welcome to the 15th Easy jQuery Tutorial, part of EasyProgramming.net. We learned two ways of getting data from a web service. This is the final way that I will show you how to get data. We're simply using the $.ajax() method. You can consider this a kind of catch-all method because it's extremely flexible. You can change the method type, send in data for the web service to respond to, and more. I'd recommend reaching the API docs on ajax to learn about all the functionality.

As I did last time, I would recommend checking out the AJAX videos I did in the Easy JavaScript series.

Here's a quick example of what an $.ajax() method implementation looks like.

 
 $.ajax({
 url: 'easyprogramming.net',
 method: 'GET',
 dataType: 'json',
 data: {
 testData: 'testdata'
 },
 success: function(result) {
 //do something with result
 }
 });

The url is the url that you are getting information from. 

The method is the HTTP method that you want to use. You can use GET, POST, PUT, or DELETE. There are other HTTP methods that you can use but in this series, I will only be going over these four. 

The data is what you are sending in your request to the server. It can be one thing or multiple items in JSON format. It is optional.

The success property is looking fora callback function. The function can accept the resulting data and do things to it. In this video, we will once again output to a table.

The dataType property specifies what type of data to expect. They can be JSON, text, xml, html, or it can be left out and the method will get whatever data comes its way.

You can also chain the done, fail, and always methods to the end but we will not be covering those in this tutorial.

You can use the following Easy Programming dummy JSON file for practice: https://www.easyprogramming.net/heroes.json

I hope you enjoyed this tutorial! Please feel free to ask questions below or just leave your comments.

To fork the fiddle and follow along: https://jsfiddle.net/easyjs/tnpshm36/

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!

Resources:



Comments: