Chuyển tới nội dung
Home » Call Web Api Using Jquery Ajax | How To Send Api Requests Using Jquery

Call Web Api Using Jquery Ajax | How To Send Api Requests Using Jquery

Call web api service with basic authentication using jquery ajax

Consuming Web API Service From jQuery

In this article, I am going to discuss how to Consuming Web API Service From jQuery. We are going to work with the same example that we created in our previous article where we discussed Parameter Binding in WEB API. So please read our previous article before proceeding with this article.

Business Requirements:

When we click on the “Get All Employees” button, then we need to retrieve all the employee’s information and then display this information in an unordered list as shown in the image below. When we click on the “Clear” button then we need to clear the employees from the unordered list.

Let’s discuss how to consuming ASP.NET Web API Service From jQuery

Modify the Employee Controller of our project as shown below where we create one action which will return the list of employees.

namespace WEB_API_Using_AJAX.Controllers { public class EmployeeController : ApiController { [HttpGet] public IEnumerable

GetEmployees() { EmployeeDBContext dbContext = new EmployeeDBContext(); return dbContext.Employees.ToList(); } } }

Then modify the WebApiConfig class which is present in the inside App_Start folder as shown below. Here we are changing the URI pattern to allow action name as part of the URL.

public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: “DefaultApi”, routeTemplate: “api/{controller}/{action}/{id}”, defaults: new { id = RouteParameter.Optional } ); } }

Let’s add one Html Page to our project with the name HtmlPage1.html

Right-click on the project and then select Add => Html page as shown below

In the next pop up specify the name for the HTML page and then click on the Ok button as shown in the image below

Once you created the page then copy and paste the following code in it.

That’s it; now run the application and navigate to the following URL in the browser

http://localhost:xxxxx/htmlpage1.html (instead of xxxxx you need to provide the port number where your application is running). It will display the following page.

Once you click on Get All Employees button it will display the employees data as unordered list as shown below on the below page.

In this example, both the client (i.e. the HTML page that contains the AJAX code) and the ASP.NET Web API service are present in the same project so it worked without any problem. But, if they are present in different projects then this wouldn’t work.

In the next article, we will discuss Why the AJAX call wouldn’t work if the client and service are present in different projects and then we will discuss how to make it work. Here, in this article, I try to explain How to Consuming ASP.NET Web API From jQuery AJAX step by step with a simple example. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

i have request


$(function(){ $.ajax({ type: 'GET', dataType:"jsonp", url: "http://localhost:8000/api/admin/announces", headers:{ 'Authorization' : 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBWZXIiOiIwLjAuMCIsImV4cCI6NDcyNjM4OTEyMiwibG9jYWxlIjoiIiwibWFzdGVyVmVyIjoiIiwicGxhdGZvcm0iOiIiLCJwbGF0Zm9ybVZlciI6IiIsInVzZXJJZCI6IiJ9.QIZbmB5_9Xlap_gDhjETfMI6EAmR15yBtIQkWFWJkrg', 'Content-Type':'application/json' }, succces: function(data){ console.log('success',data); } }); });

and i having 400 bad request error net::ERR_ABORTED 400 (Bad Request). What am I missing ?

In this article, we will discuss how to invoke API, using AJAX in ASP.NET .Core. This article will explain how to create Web API in ASP.NET Core and call that Web API, using jQuery AJAX in Razor.Milestone

  • Create a simple ASP.NET Core Web Application project.
  • Add a Model.
  • Create Web API returning list of the data.
  • Create a new Controller and View.
  • Write jQuery AJAX code to invoke Web API and parse into HTML.

Create simple ASP.NET Core Web Application.Creating a Web Application is similar to creating a ASP.NET MVC Web Application.Step 1 Open Visual Studio.

Step 2 Go to File => New Project.

  1. Select Visual C# => .NET Core => ASP.NET Core Web Application(.NET Core).
  2. Name your Solution (DemoApp), Project (DemoApp) and click OK.
  1. Select Web Application.
  2. Change Authentication to Individual Accounts.

Now, Visual Studio 2017 will create a project for you. Once the project is created, you will see the screen, as shown below.

Add ModelStep 1Create a new folder under Models folder named Student.

Step 2Add New Class named as PersonalDetail.Step 3Add the lines of codes given below to PersonalDetail class.

Code sample

  1. public class PersonalDetail
  2. public string RegNo { get; set; }
  3. public string Name { get; set; }
  4. public string Address { get; set; }
  5. public string PhoneNo { get; set; }
  6. public DateTime AdmissionDate { get; set; }

Add Web APIStep 1Right click on Controller Folder and Add => Controller.

Step 2Select API Controller – Empty.Step 3Click Add.

Step 4Name the Web API as StudentAPI.

Step 5Now, create [HttpGet] type method called GetAllStudents().

Your method should look, as shown below.

Code sample

  1. public class StudentAPIController : Controller
  2. [HttpGet]
  3. public IEnumerable GetAllStudents()
  4. List students = new List
  5. new PersonalDetail{
  6. RegNo = “2017-0001”,
  7. Name = “Nishan”,
  8. Address = “Kathmandu”,
  9. PhoneNo = “9849845061”,
  10. AdmissionDate = DateTime.Now
  11. },
  12. new PersonalDetail{
  13. RegNo = “2017-0002”,
  14. Name = “Namrata Rai”,
  15. Address = “Bhaktapur”,
  16. PhoneNo = “9849845062”,
  17. AdmissionDate = DateTime.Now
  18. },
  19. };
  20. return students;

Call Web API using Jquery AJAXCreating Controller and View

You can create a new controller and view for displaying the data returned by Web API. For Now I used Index Method of Home Controller to call Web API just created.

Step 1

Open Views => Home => Index.cshtml

Step 2

Lets remove unnecessady HTML codes.

Step 3

Add Reference to Jquery.

Step 4

Let’s add a simple HTML Table to display data returned from Web API in tablular form.

Code sample

  1. //Reference to JQuery
  2. Test Data from API


Regd No


Name


Address


Phone No


Admission Date

Step 5

Let’s add jQuery scripts to call Web API, which we just created and parse the data sent by API to HTML. AJAX looks, as shown below.

Code sample

More about jQuery AJAX

AJAX is a developer’s dream(Defn from W3Schools), because you can

  • Update a Web page without reloading the page.
  • Request data from a server – after the page has loaded.
  • Receive data from a server – after the page has loaded.
  • Send the data to a Server – in the background.

To learn the basics of AJAX, please visit https://www.w3schools.com/xml/ajax_intro.asp

Parts of AJAX

type: GET/POST

url : URL ofWeb API to pull/push data

contentType: application/json

dataType: json

success: function()

failure: function()

error: function()

Application Execution

Now, run the Index Mthod of Home Page Controller and you will be able to retrieve all the data passed from Web API. If you navigate to the Web API, which we just created, it looks as shown below.

Now, let’s navigate to Index Method of Home Contoller (Where we load WebAPI using JQuery AJAX)

JSON data shown above is parsed here.

Checking data, using Browser console

Let’s check the data shown above, using Browser console too. The data in the console looks as shown below.

If you like to show the data only after clicking any buttons, you can customize the script section to load the data.

Summary

I hope you learned:

Web API with AJAX

It has a few limitations, such as only being able to be consumed by HTTP and being able to host on IIS. Then WCF took entries with valuable features. The limitation of IIS has gone, and people started to host their applications in various environments. Then new problems began. It’s a programmer’s nightmare to configure endpoints and consume them through a proper endpoint (If you are a good developer, you may ignore the line you have read just now). Then Microsoft introduced the concept of the Web API in MVC platforms on top of the traditional ASP.NET.

The Web API is a Swiss knife with many features and capabilities. It has simplified the concept of communication. And supports true RESTful features. The most beautiful advantage of the Web API is (almost) any client can consume it. Whether your client is built using C#, JavaScript, or another language running on various platforms and devices does not matter. We will not continue our explanation much more because this is not core to a Web API article. So, let’s start our coding session by assuming you have a basic understanding of HTTP POST, GET, PUT, and DELETE verbs to talk about Web API applications.

Per the title, we will understand how to consume the Web API service using a POST method. If you are new in this environment (read Web API and RESTful service) and still want to read, the following paragraph is for you.

When discussing RESTful services, we need to consider every object a resource. For example, we want to read the employee information whose id is 5, so the information is nothing but a resource. If I want to get the picture whose name is “flower”, then I think of the picture as nothing but a resource that a few HTTP verbs can consume. In a broad sense, consume implies save, retrieve, update, and delete. Now, our beloved CRUD operation can match with the HTTP verb. Here is the mapping sequence:

  • POST: Create
  • GET: Read
  • PUT: Update
  • DELETE: delete

So, the idea is that when we perform a create operation, we will use the POST verb with respect to the RESTful service, and in this article, we will use the jQuery ajax() function for the post-operation.

As per the concept of any service application, we must implement both a client and a server. Here we will implement the client using JavaScript and JQuey. So, let’s start to write the code.

Call web api service with basic authentication using jquery ajax
Call web api service with basic authentication using jquery ajax

Conclusion

Mastering API requests with jQuery unlock a wealth of opportunities for developers seeking efficient and seamless communication with APIs. Its user-friendly nature, broad cross-browser support, and capacity to abstract complexities make it an ideal choice for both novices and experienced developers.

The integration of Apidog further enriches the jQuery API request process, empowering developers to effortlessly generate code and maintain uniformity across their projects. By harnessing jQuery and Apidog in harmony, developers can elevate their API communication capabilities, resulting in more efficient, sustainable, and error-resistant code within an intuitive interface.

By pre-testing the API through Apidog and leveraging the code generation workflow, a robust API call implementation can be rapidly constructed. This approach enhances efficiency and facilitates the seamless integration of APIs into web applications, empowering developers to deliver stable and reliable solutions in a shortened timeframe.

jQuery – AJAX get() and post() Methods

The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.

Implement client code to consume Web API

This is the client-side implementation to consume the Web API service. We are loading jQuery from the local server and using the ajax() function.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>


Name :-
Surname:-



Please note the formation of the data we collect from the HTML form. Since we have configured the ajax() method to communicate with the JSON data, we need to form the data in object format. So, this is the implementation of the client-side code.

#ajax #jquery #web #api Web API call using jQuery AJAX Video Tutorial
#ajax #jquery #web #api Web API call using jQuery AJAX Video Tutorial

Why do we use jQuery to call API?

jQuery is the preferred choice for calling APIs due to its ability to provide a concise and user-friendly syntax for making AJAX requests. This feature makes it particularly attractive to developers, as it simplifies the process of interacting with APIs. Furthermore, jQuery’s cross-browser compatibility ensures consistent behavior across different browsers, eliminating the need for developers to write separate code for each browser. This not only saves time but also reduces the likelihood of compatibility issues.

Another key advantage of using jQuery for API calls is its simplicity, which significantly reduces the amount of code needed to perform these requests. This streamlined approach enhances the efficiency of development, as developers can achieve the same results with fewer lines of code. Moreover, jQuery abstracts away many of the complexities of AJAX, making it accessible to both beginners and experienced developers alike. This abstraction allows developers to focus on the core functionality of their applications without getting bogged down in the intricacies of AJAX implementation.

Conclusion

This is the first lap of our Web API Ajax journey. Today we have learned the POST method and its practical implementation of that. In a future article, we will learn all types of HTTP verbs and a few concepts of Web API. Happy learning.

Gọi Web API sử dụng Ajax JQuery

Đăng lúc: 09:41 AM – 08/12/2022 bởi Charles Chung – 615

Trong bài viết này tôi sẽ hướng dẫn các bạn các GET, POST, PUT, DELETE dữ liệu lên Web API sử dụng Ajax JQuery và lưu vào database, trong đó có cả post dữ liệu dạng MultiplePart và cấu hình CORS trên Web API.

Cấu hình CORS trên ASP.NET Core Web API 3.1

  • Trong tệp Startup.cs tìm phương thức ConfigureServices bổ sung dòng cấu hình sau

services.AddCors(o => {o.AddPolicy(“AllowOrigin”, p =>{p.AllowAnyOrigin()

.AllowAnyHeader()

.AllowAnyMethod();});});

  • Nếu cần cấu hình rõ từng thông số thì dùng lệnh bên dưới kết hợp các thông số cho phép

p.WithOrigins(“https://hanam88.com”)

.WithMethods(“GET”,”POST”,”DELETE”)

.WithHeaders(“Authorize”);

  • Vẫn trong tệp Startup.cs tìm phương thức Configure bổ sung thêm dòng

app.UseCors(“AllowOrigin”);

  • Trong các controller api bổ sung thuộc tính sau [EnableCors(“AllowOrigin”)] ví dụ cho ProductController

[EnableCors(“AllowOrigin”)]

public class ProductsController : ControllerBase

Lưu ý khi POST data lên Web API

  • Khi post dữ liệu FormData lên Web API để web-security của trình duyệt bỏ qua việc xử lý dữ liệu và kiểu nội dung, bạn cần thiết lập thông số processData:false, contentType:false trong lệnh ajax. Ví dụ

$.ajax({

url:domain+”/bkap/san-pham/them-voi-image”,

type:’POST’,

data:fd,

processData:false,

contentType:false,

success:function(data){

if(typeof(data)==’string’)

alert(data);

}else{

//in thông tin sản phẩm…

alert(“Đã thêm thành công sản phẩm có tên: “+ data.productName);

$(‘#modalAdd’).modal(‘hide’);

window.location.reload();

},

error:function(msg)

alert(msg);

});

Video demo

Link tải source code (Google Drive) pass hỏi thầy Charles Chung

thay lời cảm ơn!

Các bài cũ hơn
  • Tìm hiểu Bridge Design Pattern với ví dụ sử dụng ngôn ngữ C# (08:57 PM – 06/12/2022)
  • Cách GET-POST dữ liệu Multipart lên Web API trong ASP.NET Core (10:22 AM – 02/12/2022)
  • Upload ảnh kèm dữ liệu JSON trong ASP.NET Core Web API (09:25 AM – 01/12/2022)
  • Tìm hiểu Adapter Design Pattern với ví dụ sử dụng ngôn ngữ C# (05:03 PM – 30/11/2022)
  • Truy xuất cơ sở dữ liệu sử dụng Entity Framework Core trong ASP.NET Core Web API (02:40 PM – 29/11/2022)
In this article I will explain with an example, how to call (consume) Web API using jQuery AJAX in ASP.Net Core MVC.
This article will explain how to make a jQuery POST call to Web API Controller’s method using jQuery AJAX in ASP.Net Core MVC.

What is Web API in .Net Core?

ASP.Net Core Web API is a framework to build HTTP services which can be consumed by cross platform clients including desktops or mobile devices irrespective of the Browsers or Operating Systems being used.

ASP.Net Core Web API supports RESTful applications and uses GET, PUT, POST, DELETE verbs for client communications.

Model

Following is a Model class named PersonModel with two properties i.e. Name and DateTime.

public class PersonModel

///

/// Gets or sets Name.

///

public string Name { get; set; }

///

/// Gets or sets DateTime.

///

public string DateTime { get; set; }

Web API Controller

In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.

Now from the Add Scaffold window, choose the API Controller – Empty option as shown below.

Then give it a suitable name and click Add.

Action Method

The next step is to add an Action Method to the Web API Controller.

The Web API Controller consists of a method named AjaxMethod which accepts an object of PersonModel and updates the DateTime property with the Current Date and Time and returns it back.

This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpPost attribute which signifies that the method will accept Http Post requests.

[Route(“api/[controller]”)]

[ApiController]

public class AjaxAPIController : ControllerBase

[Route(“AjaxMethod”)]

[HttpPost]

public PersonModel AjaxMethod(PersonModel person)

person.DateTime = DateTime.Now.ToString();

return person;

Controller

Now you will need to add one empty Controller along with a View. The View will be used for calling the Web API 2 Controller’s method using jQuery AJAX.

The Controller consists of an empty Action method which simply returns the View.

public class HomeController : Controller

// GET: Home

public IActionResult Index()

return View();

View

The View consists of an HTML TextBox element and a Button. The Button has been assigned a jQuery click event handler and when the Button is clicked a jQuery AJAX call is made to the Web API 2 Controller’s method.
The URL for the jQuery AJAX call is set to the Web API 2 Controller’s method i.e. /api/AjaxAPI/AjaxMethod. The value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.

@{

Layout = null;

<br /> Index<br />

Configuring the JSON Serializer setting

The above program will work but you will see undefined values in the JavaScript Alert Message Box.

In order to resolve it, the JSON Serializer settings need to be configured in the Startup.cs file.

1. Open the Startup.cs class from the Solution Explorer window.

2. Add the following namespace.

using Newtonsoft.Json.Serialization;

3. Then inside the ConfigureServices method, you will have to add the following code which will instruct the program to use Newtonsoft library for JSON serialization.

public void ConfigureServices(IServiceCollection services)

services.AddMvc()

.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

Screenshot

Downloads

Back to: ASP.NET Web API Tutorials For Beginners and Professionals

Call Web API using AJAX | JQuery Ajax Method
Call Web API using AJAX | JQuery Ajax Method

Generating jQuery API request code with Apidog

Apidog is a powerful tool that can automatically generate business code for various languages and frameworks, including jQuery. This feature is particularly useful when you need to make API requests. With just a few clicks, Apidog can generate the jQuery code needed to send an API request, saving you time and reducing the chance of errors. This makes Apidog an invaluable tool for developers who want to streamline their workflow and increase efficiency.

Follow these steps to generate jQuery code seamlessly:

Step 1: Open Apidog

Open Apidog and navigate to the “API Requests” section, select the API endpoint you want to interact with then click on the “Generate Code” button.

Step 2: Choose jQuery as the target language

Choose jQuery as the target language and Apidog will generate the jQuery code snippet for your selected API request.

Using generated jQuery code to send API requests.

Now armed with the generated jQuery code, integrating it into your project is straightforward. Here’s an example of an HTML page that uses jQuery to make an AJAX request and display the result on the page:


<br /> jQuery AJAX Example<br />

jQuery AJAX Example



In this scenario, the jQuery library is added to the webpage using a script tag from a content delivery network (CDN). Subsequently, a script block is employed to initiate an AJAX request to the designated URL, utilizing the specified settings. Upon successful completion of the request, the response is showcased on the webpage within a div element identified by the id “result”.

jQuery $.post() Method

The

$.post()

method requests data from the server using an HTTP POST request.

Syntax:

The required URL parameter specifies the URL you wish to request.

The optional data parameter specifies some data to send along with the request.

The optional callback parameter is the name of a function to be executed if the request succeeds.

The following example uses the

$.post()

method to send some data along with the
request:

Example

$.post(“demo_test_post.asp”,

name: “Donald Duck”,

city: “Duckburg”

},

function(data, status){

alert(“Data: ” + data + “\nStatus: ” + status);

});

});

The first parameter of

$.post()

is the URL we wish to request (“demo_test_post.asp”).

Then we pass in some data to send along with the request (name and city).

The ASP script in “demo_test_post.asp” reads the parameters, processes them, and returns a result.

The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

Tip: Here is how the ASP file looks like (“demo_test_post.asp”):

dim fname,city

fname=Request.Form(“name”)

city=Request.Form(“city”)

Response.Write(“Dear ” & fname & “. “)

Response.Write(“Hope you live well in ” & city & “.”)

%>

Call a  Web API From Jquery AJAX
Call a Web API From Jquery AJAX

jQuery $.get() Method

The

$.get()

method requests data from the server with an HTTP GET request.

Syntax:

The required URL parameter specifies the URL you wish to request.

The optional callback parameter is the name of a function to be executed if the request succeeds.

The following example uses the

$.get()

method to retrieve data from a file on
the server:

Example

$.get(“demo_test.asp”, function(data, status){

alert(“Data: ” + data + “\nStatus: ” + status);

});

});

The first parameter of

$.get()

is the URL we wish to request (“demo_test.asp”).

The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

Tip: Here is how the ASP file looks like (“demo_test.asp”):

response.write(“This is some text from an external ASP file.”)

%>

How to use jQuery to send API requests

jQuery provides a straightforward and efficient way to send API requests from your web application. In this tutorial, we will walk through the process of using jQuery to make AJAX requests to an API endpoint. By the end of this tutorial, you will have a clear understanding of how to use jQuery to interact with APIs and handle the responses.

Step 1: Include jQuery Library

First, ensure that you have included the jQuery library in your HTML file. You can do this by adding the following line within the tags of your HTML document:

Step 2: Write the AJAX Request

Use jQuery’s AJAX function to send the API request. The AJAX function allows you to make asynchronous HTTP requests to the server. Here’s an example of how you can use the AJAX function to send a GET request to an API endpoint:


$.ajax({ url: 'https://api.example.com/data', method: 'GET', success: function(response) { // Handle the API response here console.log(response); }, error: function(xhr, status, error) { // Handle errors here console.error(status, error); } });

Step 3: Customize the Request

You can customize the AJAX request by specifying various parameters such as the request method (GET, POST, PUT, DELETE), data to be sent, headers, and more. For example, if you need to send data with a POST request, you can include a

data

parameter in the AJAX call.

Step 4: Handle the API Response

Inside the

success

function of the AJAX call, you can handle the API response. This is where you can process the data returned by the API and update your web page accordingly.

By following these steps, you can use jQuery to send API requests and handle the responses in your web application. Remember to replace

'https://api.example.com/data'

with the actual URL of the API endpoint you want to access and customize the AJAX call according to the specific requirements of your API.

Call (Consume) Web API using jQuery AJAX in ASP.Net MVC
Call (Consume) Web API using jQuery AJAX in ASP.Net MVC

HTTP Request: GETPOST

Two commonly used methods for a request-response between a client and server are: GET and POST.

  • GET – Requests data from a specified resource
  • POST – Submits data to be processed to a specified resource

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.

POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

To learn more about GET and POST, and the differences between the two methods, please read our HTTP Methods GET vs POST chapter.

Use the post() function of the jQuery library

Here is another way to perform the POST operation. We can use the post() function to perform the post-operation. The post() function is nothing but a shorthand implementation of the ajax() function.

Have a look at the following code.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>

Name :-
Surname:-


Here is the output of the post() method.

Consume .NET 5 Web API Using jQuery Ajax
Consume .NET 5 Web API Using jQuery Ajax

Learning By Doing

To demonstrate how to make API calls via a frontend client with JQuery, we’ll be walking through how to create link previews using the LinkPreview API. This service serves as a good tutorial because:

  • It’s an example of a simple GET endpoint
  • There’s a quick and immediately useful end result
  • It’s free

Tell me That Ain’t Insecurr

I want to stress here that we’re doing this for the sake of learning; while this is probably the fastest way to start working with an API, it is most definitely not secure.

Making calls with private keys stored and passed via the client side exposes your key publicly. In a production environment, this is like shoving your password in people’s faces. People will most definitely want to steal and exploit your private key: if what you were doing didn’t have any value, it wouldn’t require a key in the first place.

Hopefully, this has scared you enough to consider passing credentials. That said, there’s another solid reason we selected LinkPreview as today’s example. LinkPreview offers domain whitelisting for requests, so even if somebody did steal your key, they’d only be able to use it from your domain ;).

jQuery.ajax( url [, settings ] )Returns: jqXHR

Description: Perform an asynchronous HTTP (Ajax) request.

  • version added: 1.5jQuery.ajax( url [, settings ] )
    • urlA string containing the URL to which the request is sent.
    • settingsA set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings.
  • version added: 1.0jQuery.ajax( [settings ] )
    • settingsA set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().

      • accepts (default:

        depends on dataType

        )A set of key/value pairs that map a given

        dataType

        to its MIME type, which gets sent in the

        Accept

        request header. This header tells the server what kind of response it will accept in return. For example, the following defines a custom type

        mycustomtype

        to be sent with the request:12345678910111213141516

        $.ajax({


        accepts: {


        mycustomtype: 'application/x-some-custom-type'


        },


        // Instructions for how to deserialize a `mycustomtype`


        converters: {


        'text mycustomtype': function(result) {


        // Do Stuff


        return newresult;


        },


        // Expect a `mycustomtype` back from server


        dataType: 'mycustomtype'


        });


        converters

        for this to work properly.
      • async (default:

        true

        )By default, all requests are sent asynchronously (i.e. this is set to

        true

        by default). If you need synchronous requests, set this option to

        false

        . Cross-domain requests and

        dataType: "jsonp"

        requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of

        async: false

        with jqXHR (

        $.Deferred

        ) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as

        jqXHR.done()

        .
      • beforeSendType: Function( jqXHR jqXHR, PlainObject settings )A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning

        false

        in the

        beforeSend

        function will cancel the request. As of jQuery 1.5, the

        beforeSend

        option will be called regardless of the type of request.
      • cache (default:

        true, false for dataType 'script' and 'jsonp'

        )If set to

        false

        , it will force requested pages not to be cached by the browser. Note: Setting

        cache

        to false will only work correctly with HEAD and GET requests. It works by appending “_={timestamp}” to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.
      • completeA function to be called when the request finishes (after

        success

        and

        error

        callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request (

        "success"

        ,

        "notmodified"

        ,

        "nocontent"

        ,

        "error"

        ,

        "timeout"

        ,

        "abort"

        , or

        "parsererror"

        ). As of jQuery 1.5, the

        complete

        setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
      • contentsAn object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5)
      • contentType (default:

        'application/x-www-form-urlencoded; charset=UTF-8'

        )When sending data to the server, use this content type. Default is “application/x-www-form-urlencoded; charset=UTF-8”, which is fine for most cases. If you explicitly pass in a content-type to

        $.ajax()

        , then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass

        false

        to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than

        application/x-www-form-urlencoded

        ,

        multipart/form-data

        , or

        text/plain

        will trigger the browser to send a preflight OPTIONS request to the server.
      • contextThis object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call (

        $.ajaxSettings

        merged with the settings passed to

        $.ajax

        ). For example, specifying a DOM element as the context will make that the context for the

        complete

        callback of a request, like so:123456

        $.ajax({


        url: "test.html",


        context: document.body


        }).done(function() {


        $( this ).addClass( "done" );


        });
      • converters (default:

        {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}

        )An object containing dataType-to-dataType converters. Each converter’s value is a function that returns the transformed value of the response. (version added: 1.5)
      • crossDomain (default:

        false for same-domain requests, true for cross-domain requests

        )If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to

        true

        . This allows, for example, server-side redirection to another domain. (version added: 1.5)
      • dataType: PlainObject or String or Array

        Data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the


        data

        is appended to the URL.

        When


        data

        is an object, jQuery generates the data string from the object’s key/value pairs unless the

        processData

        option is set to

        false

        . For example,

        { a: "bc", d: "e,f" }

        is converted to the string

        "a=bc&d=e%2Cf"

        . If the value is an array, jQuery serializes multiple values with same key based on the value of the

        traditional

        setting (described below). For example,

        { a: [1,2] }

        becomes the string

        "a%5B%5D=1&a%5B%5D=2"

        with the default

        traditional: false

        setting.

        When


        data

        is passed as a string it should already be encoded using the correct encoding for

        contentType

        , which by default is

        application/x-www-form-urlencoded

        .

        In requests with


        dataType: "json"

        or

        dataType: "jsonp"

        , if the string contains a double question mark (

        ??

        ) anywhere in the URL or a single question mark () in the query string, it is replaced with a value generated by jQuery that is unique for each copy of the library on the page (e.g.

        jQuery21406515378922229067_1479880736745

        ).

      • dataFilterA function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the ‘dataType’ parameter.
      • dataType (default:

        Intelligent Guess (xml, json, script, or html)

        )The type of data that you’re expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:


        • "xml"

          : Returns a XML document that can be processed via jQuery.

        • "html"

          : Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

        • "script"

          : Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter,

          _=[TIMESTAMP]

          , to the URL unless the

          cache

          option is set to

          true

          . Note: This will turn POSTs into GETs for remote-domain requests. Prior to jQuery 3.5.0, unsuccessful HTTP responses with a script

          Content-Type

          were still executed.

        • "json"

          : Evaluates the response as JSON and returns a JavaScript object. Cross-domain

          "json"

          requests that have a callback placeholder, e.g.

          ?callback=?

          , are performed using JSONP unless the request includes

          jsonp: false

          in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of

          null

          or

          {}

          instead. (See json.org for more information on proper JSON formatting.)

        • "jsonp"

          : Loads in a JSON block using JSONP. Adds an extra

          "?callback=?"

          to the end of your URL to specify the callback. Disables caching by appending a query string parameter,

          "_=[TIMESTAMP]"

          , to the URL unless the

          cache

          option is set to

          true

          .

        • "text"

          : A plain text string.
        • multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use

          "text xml"

          for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML:

          "jsonp text xml"

          . Similarly, a shorthand string such as

          "jsonp xml"

          will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
      • errorA function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides

        null

        ) are

        "timeout"

        ,

        "error"

        ,

        "abort"

        , and

        "parsererror"

        . When an HTTP error occurs,

        errorThrown

        receives the textual portion of the HTTP status, such as “Not Found” or “Internal Server Error.” (in HTTP/2 it may instead be an empty string) As of jQuery 1.5, the

        error

        setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain scripts and cross-domain JSONP requests. This is an Ajax Event.
      • global (default:

        true

        )Whether to trigger global Ajax event handlers for this request. The default is

        true

        . Set to

        false

        to prevent the global handlers like

        ajaxStart

        or

        ajaxStop

        from being triggered. This can be used to control various Ajax Events.
      • headers (default:

        {}

        )An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header

        X-Requested-With: XMLHttpRequest

        is always added, but its default

        XMLHttpRequest

        value can be changed here. Values in the

        headers

        setting can also be overwritten from within the

        beforeSend

        function. (version added: 1.5)
      • ifModified (default:

        false

        )Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is

        false

        , ignoring the header. In jQuery 1.4 this technique also checks the ‘etag’ specified by the server to catch unmodified data.
      • isLocal (default:

        depends on current location protocol

        )Allow the current environment to be recognized as “local,” (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local:

        file

        ,

        *-extension

        , and

        widget

        . If the

        isLocal

        setting needs modification, it is recommended to do so once in the

        $.ajaxSetup()

        method. (version added: 1.5.1)
      • jsonpOverride the callback function name in a JSONP request. This value will be used instead of ‘callback’ in the ‘callback=?’ part of the query string in the url. So

        {jsonp:'onJSONPLoad'}

        would result in

        'onJSONPLoad=?'

        passed to the server. As of jQuery 1.5, setting the

        jsonp

        option to

        false

        prevents jQuery from adding the “?callback” string to the URL or attempting to use “=?” for transformation. In this case, you should also explicitly set the

        jsonpCallback

        setting. For example,

        { jsonp: false, jsonpCallback: "callbackName" }

        . If you don’t trust the target of your Ajax requests, consider setting the

        jsonp

        property to

        false

        for security reasons.
      • jsonpCallbackSpecify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it’ll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of

        jsonpCallback

        is set to the return value of that function.
      • method (default:

        'GET'

        )The HTTP method to use for the request (e.g.

        "POST"

        ,

        "GET"

        ,

        "PUT"

        ). (version added: 1.9)
      • mimeTypeA mime type to override the XHR mime type. (version added: 1.5.1)
      • passwordA password to be used with XMLHttpRequest in response to an HTTP access authentication request.
      • processData (default:

        true

        )By default, data passed in to the

        data

        option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type “application/x-www-form-urlencoded”. If you want to send a DOMDocument, or other non-processed data, set this option to

        false

        .
      • scriptAttrsDefines an object with additional attributes to be used in a “script” or “jsonp” request. The key represents the name of the attribute and the value is the attribute’s value. If this object is provided it will force the use of a script-tag transport. For example, this can be used to set

        nonce

        ,

        integrity

        , or

        crossorigin

        attributes to satisfy Content Security Policy requirements. (version added: 3.4)
      • scriptCharsetOnly applies when the “script” transport is used. Sets the

        charset

        attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. Alternatively, the

        charset

        attribute can be specified in

        scriptAttrs

        instead, which will also ensure the use of the “script” transport.
      • statusCode (default:

        {}

        )

        An object of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

        1234567

        $.ajax({


        statusCode: {


        404: function() {


        alert( "page not found" );


        });

        If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the

        (version added: 1.5)

        error

        callback.

      • successA function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the

        dataType

        parameter or the

        dataFilter

        callback function, if specified; a string describing the status; and the

        jqXHR

        (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
      • timeoutType: NumberSet a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the

        $.ajax

        call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.
      • traditionalSet this to

        true

        if you wish to use the traditional style of param serialization.
      • type (default:

        'GET'

        )An alias for

        method

        . You should use

        type

        if you’re using versions of jQuery prior to 1.9.0.
      • url (default:

        The current page

        )A string containing the URL to which the request is sent.
      • usernameA username to be used with XMLHttpRequest in response to an HTTP access authentication request.
      • xhr (default:

        ActiveXObject when available (IE), the XMLHttpRequest otherwise

        )Type: Function()Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.
      • xhrFields

        An object of fieldName-fieldValue pairs to set on the native


        XHR

        object. For example, you can use it to set

        withCredentials

        to

        true

        for cross-domain requests if needed.123456

        $.ajax({


        url: a_cross_domain_url,


        xhrFields: {


        withCredentials: true


        });

        In jQuery 1.5, the

        (version added: 1.5.1)

        withCredentials

        property was not propagated to the native

        XHR

        and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it.

The

$.ajax()

function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like

$.get()

and

.load()

are available and are easier to use. If less common options are required, though,

$.ajax()

can be used more flexibly.

At its simplest, the

$.ajax()

function can be called with no arguments:

Note: Default settings can be set globally by using the

$.ajaxSetup()

function.

This example, using no options, loads the contents of the current page, but does nothing with the result. To use the result, you can implement one of the callback functions.

The jqXHR Object

The jQuery XMLHttpRequest (jqXHR) object returned by

$.ajax()

as of jQuery 1.5 is a superset of the browser’s native XMLHttpRequest object. For example, it contains

responseText

and

responseXML

properties, as well as a

getResponseHeader()

method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the

jqXHR

object simulates native XHR functionality where possible.

As of jQuery 1.5.1, the

jqXHR

object also contains the

overrideMimeType()

method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The

.overrideMimeType()

method may be used in the

beforeSend()

callback function, for example, to modify the response content-type header:

10

11

The jqXHR objects returned by

$.ajax()

as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the

$.ajax()

request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

  • jqXHR.done(function( data, textStatus, jqXHR ) {});

    An alternative construct to the success callback option, refer to


    deferred.done()

    for implementation details.

  • jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

    An alternative construct to the error callback option, the


    .fail()

    method replaces the deprecated

    .error()

    method. Refer to

    deferred.fail()

    for implementation details.

  • jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); (added in jQuery 1.6)

    An alternative construct to the complete callback option, the


    .always()

    method replaces the deprecated

    .complete()

    method.

    In response to a successful request, the function’s arguments are the same as those of


    .done()

    : data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of

    .fail()

    : the jqXHR object, textStatus, and errorThrown. Refer to

    deferred.always()

    for implementation details.

  • jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

    Incorporates the functionality of the


    .done()

    and

    .fail()

    methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to

    deferred.then()

    for implementation details.

Deprecation Notice: The

jqXHR.success()

,

jqXHR.error()

, and

jqXHR.complete()

callbacks are removed as of jQuery 3.0. You can use

jqXHR.done()

,

jqXHR.fail()

, and

jqXHR.always()

instead.

10

11

12

13

14

15

16

17

18

19

The

this

reference within all callbacks is the object in the

context

option passed to

$.ajax

in the settings; if

context

is not specified,

this

is a reference to the Ajax settings themselves.

For backward compatibility with

XMLHttpRequest

, a

jqXHR

object will expose the following properties and methods:


  • readyState

  • responseXML

    and/or

    responseText

    when the underlying request responded with xml and/or text, respectively

  • status

  • statusText

    (may be an empty string in HTTP/2)

  • abort( [ statusText ] )

  • getAllResponseHeaders()

    as a string

  • getResponseHeader( name )

  • overrideMimeType( mimeType )

  • setRequestHeader( name, value )

    which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one

  • statusCode( callbacksByStatusCode )

No

onreadystatechange

mechanism is provided, however, since

done

,

fail

,

always

, and

statusCode

cover all conceivable requirements.

Callback Function Queues

The

beforeSend

,

error

,

dataFilter

,

success

and

complete

options all accept callback functions that are invoked at the appropriate times.

As of jQuery 1.5, the

fail

and

done

, and, as of jQuery 1.6,

always

callback hooks are first-in, first-out managed queues, allowing for more than one callback for each hook. See Deferred object methods, which are implemented internally for these

$.ajax()

callback hooks.

The callback hooks provided by

$.ajax()

are as follows:


  1. beforeSend

    callback option is invoked; it receives the

    jqXHR

    object and the

    settings

    object as parameters.

  2. error

    callback option is invoked, if the request fails. It receives the

    jqXHR

    , a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: “abort”, “timeout”, “No Transport”.

  3. dataFilter

    callback option is invoked immediately upon successful receipt of response data. It receives the returned data and the value of

    dataType

    , and must return the (possibly altered) data to pass on to

    success

    .

  4. success

    callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the

    jqXHR

    object.
  5. Promise callbacks —

    .done()

    ,

    .fail()

    ,

    .always()

    , and

    .then()

    — are invoked, in the order they are registered.

  6. complete

    callback option fires, when the request finishes, whether in failure or success. It receives the

    jqXHR

    object, as well as a string containing the success or error code.
Data Types

Different types of response to

$.ajax()

call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the

dataType

option. If the

dataType

option is provided, the Content-Type header of the response will be disregarded.

The available data types are

text

,

html

,

xml

,

json

,

jsonp

, and

script

.

If

text

or

html

is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the

responseText

property of the

jqXHR

object.

If

xml

is specified, the response is parsed using

jQuery.parseXML

before being passed, as an

XMLDocument

, to the success handler. The XML document is made available through the

responseXML

property of the

jqXHR

object.

If

json

is specified, the response is parsed using

jQuery.parseJSON

before being passed, as an object, to the success handler. The parsed JSON object is made available through the

responseJSON

property of the

jqXHR

object.

If

script

is specified,

$.ajax()

will execute the JavaScript that is received from the server before passing it on to the success handler as a string.

If

jsonp

is specified,

$.ajax()

will automatically append a query string parameter of (by default)

callback=?

to the URL. The

jsonp

and

jsonpCallback

properties of the settings passed to

$.ajax()

can be used to specify, respectively, the name of the query string parameter and the name of the JSONP callback function. The server should return valid JavaScript that passes the JSON response into the callback function.

$.ajax()

will execute the returned JavaScript, calling the JSONP callback function, before passing the JSON object contained in the response to the

$.ajax()

success handler.

For more information on JSONP, see the original post detailing its use.

Sending Data to the Server

By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the

type

option. This option affects how the contents of the

data

option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

The

data

option can contain either a query string of the form

key1=value1&key2=value2

, or an object of the form

{key1: 'value1', key2: 'value2'}

. If the latter form is used, the data is converted into a query string using

jQuery.param()

before it is sent. This processing can be circumvented by setting

processData

to

false

. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the

contentType

option from

application/x-www-form-urlencoded

to a more appropriate MIME type.

Advanced Options

The

global

option prevents handlers registered for the

ajaxSend

,

ajaxError

, and similar events from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with an

ajaxSend

handler if the requests are frequent and brief. With cross-domain script and JSONP requests, the global option is automatically set to

false

. See the descriptions of these methods below for more details.

If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the

username

and

password

options.

Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using

$.ajaxSetup()

rather than being overridden for specific requests with the

timeout

option.

By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set

cache

to

false

. To cause the request to report failure if the asset has not been modified since the last request, set

ifModified

to

true

.

The

scriptCharset

allows the character set to be explicitly specified for requests that use a

The information age is over: we have all the information now. All of it. We’re in a unique place in human history where we’ve somehow managed to mine more data than we know what to do with… and a lot of that data is easily accessible via APIs.

We’re going to get our feet wet with REST APIs today, thus allowing us to interact with meaningful information. Making Ajax GET calls with JQuery is perhaps as basic as it gets: there’s a good chance we already know all this stuff, but even I constantly forget the exact syntax of everyday functions. Chances are I’m going to come back to this post at some point to copy and paste the snippets below.

Calling ASP NET Web API service in a cross domain using jQuery ajax
Calling ASP NET Web API service in a cross domain using jQuery ajax

Introduction to REST APIs

If you’re new to executing AJAX requests, you may be new to REST APIs. This crash course will be fast and rough around the edges, so strap in.

In the most simple sense, a REST API endpoint is a URL. It just so happens that this URL probably expects more from you than simply visiting it, and as a result, should output something useful for you. API Endpoints will almost always output either JSON or XML; these responses will give you information varying from error codes to the data you seek.

REST APIs expect requests to come in one of the following forms:

  • GET: A request looking for read-only data. Some GET requests need to be copied and pasted into a browser window to receive results, but usually, we need to either authenticate or specify what we’re looking for.
  • POST: A write request to the target resource. Expects that new information will come as a result of this request.
  • PUT: Updates pre-existing data somewhere, likely in some database.
  • PATCH: Somewhat similar to PUT, and in my experience rarely used at all.
  • DELETE: Expects that information will be deleted as a result of the request

If this all seems like new information, I’d highly recommend downloading Postman to become familiar with how API calls are structured.

For now, we’ll focus on working with a simple GET endpoint.

Create Web API to serve RESTful service

In this section, we will create the Web API application. We are skipping the basic Web API creation part, hoping you know. Here is the implementation of Web API.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApplication1.WebAPI
{
public class person
{
public string name { get; set; }
public string surname { get; set; }
}
public class personController : ApiController
{
[HttpPost]
public string Post( person obj)
{
return obj.name + obj.surname;
}
}
}

At first, we created a model class (person) very similar to the client object we will send from the client application. The person controller contains the Posr() method specified with the HttpPost attribute. This implies that the POST verb can consume this action/method. We are halting the execution flow and checking the form data to the Web API.

In the Web API, we are getting the value we sent from the client end.

In the successful callback function, we just print this value to the console. Here is a sample output.

How to Call ASP.NET Core Web API using jQuery Ajax | Allow CORS Access-Control-Allow-Origin
How to Call ASP.NET Core Web API using jQuery Ajax | Allow CORS Access-Control-Allow-Origin

What’s jQuery?

jQuery is a swift, compact, and feature-rich JavaScript library that streamlines tasks such as HTML document traversal, event handling, and animation. It boasts the powerful capability of facilitating AJAX (Asynchronous JavaScript and XML) requests, enabling seamless communication with APIs. jQuery is part of a collection of functions and methods that utilize JavaScript.

Its key features include Simplified Document Object Model (DOM) operations, Convenient access to Ajax communications, Easy implementation of animations and effects, Browser differences are harmonized, Code is straightforward and easy to comprehend, and Abundance of available plugins and high expandability.

The introduction of jQuery enables the simplified authoring of complex JavaScript code, significantly enhancing development efficiency. Due to its ability to absorb browser differences and the clarity of its code, jQuery is a highly valuable library widely utilized in web front-end development. For further information, visit the official jQuery website.

Fetch Me Daddy

Get started with an API key over at LinkPreview if you’re following along. I assume you already have JQuery readily available from here forward.

To get started, we’ll wait for our document to load, and set two critical variables: the API URL, and our API key.


$( document ).ready(function() { let endpoint = 'https://api.linkpreview.net' let apiKey = '5b578yg9yvi8sogirbvegoiufg9v9g579gviuiub8' });

If you’re following along with what we’ve done with Lynx Roundups, our next step is to get all the relevant tags on a page, loop through them, and replace them with their respective link previews:


$( document ).ready(function() { let endpoint = 'https://api.linkpreview.net' let apiKey = '5b578yg9yvi8sogirbvegoiufg9v9g579gviuiub8' $( ".content a" ).each(function( index, element ) { console.log($( this ).text()); } });



tags

JQuery’s

.each

method creates a loop that iterates over every element matching the provided selector. In our example, we only want tags in the content of our page; otherwise, we would get all links, like navigation links and so forth.

Now it’s time to bring in that

$.ajax()

thing we’ve been going off about.


$( document ).ready(function() { let endpoint = 'https://api.linkpreview.net' let apiKey = '5b578yg9yvi8sogirbvegoiufg9v9g579gviuiub8' $( ".content a" ).each(function( index, element ) { $.ajax({ url: endpoint + "?key=" + apiKey + " &q=" + $( this ).text(), contentType: "application/json", dataType: 'json', success: function(result){ console.log(result); } }) }); });

This is how Ajax requests are structured: the contents of

$.ajax()

is essentially an object taking values it will use to construct the request. The above example is about as simple as it gets for making a barebones GET call. We’re looping through each tag and passing its contents (the URL) to the API, and receiving an object in response.

Ajax requests can take way more parameters than the ones we just specified. I recommend reading over the JQuery Ajax documentation closely, not only for the sake of these requests but understanding the potential items we can specify will solidify an understanding of REST APIs in general.

The line

contentType: "application/json"

specifies that the content coming back to us will be in JSON format – this is a very common header when dealing with REST APIs.

With any luck, your response should come back looking like this:


{ "title":"Google", "description":"Search webpages, images, videos and more.", "image":"https//:www.google.com/images/logo.png", "url":"https://www.google.com/" }

If you’d like to use this in a meaningful way, feel free to do something like the mess I’ve put together below:


$( document ).ready(function() { let endpoint = 'https://api.linkpreview.net' let apiKey = '5b578yg9yvi8sogirbvegoiufg9v9g579gviuiub8' $( ".content a" ).each(function( index, element ) { $.ajax({ url: endpoint + "?key=" + apiKey + " &q=" + $( this ).text(), contentType: "application/json", dataType: 'json', success: function(result){ $( element ).after( '

\n ' + '


'); $( element ).remove(); } }) }); });

That template should serve you well for most GET API calls you will make via JQuery. Go wild and see what you can do to leverage APIs and expose some people’s personal data or whatever.

If we were to truly complete this example, we’d want to refine our logic to ensure we’re not receiving nonsense. There’s no validation on what’s coming back in these calls, so there’s nothing in place to protect us if a page doesn’t comply with our format.

In this article, we will discuss how to invoke API, using AJAX in ASP.NET .Core. This article will explain how to create Web API in ASP.NET Core and call that Web API, using jQuery AJAX in Razor.Milestone

  • Create a simple ASP.NET Core Web Application project.
  • Add a Model.
  • Create Web API returning list of the data.
  • Create a new Controller and View.
  • Write jQuery AJAX code to invoke Web API and parse into HTML.

Create simple ASP.NET Core Web Application.Creating a Web Application is similar to creating a ASP.NET MVC Web Application.Step 1 Open Visual Studio.

Step 2 Go to File => New Project.

  1. Select Visual C# => .NET Core => ASP.NET Core Web Application(.NET Core).
  2. Name your Solution (DemoApp), Project (DemoApp) and click OK.
  1. Select Web Application.
  2. Change Authentication to Individual Accounts.

Now, Visual Studio 2017 will create a project for you. Once the project is created, you will see the screen, as shown below.

Add ModelStep 1Create a new folder under Models folder named Student.

Step 2Add New Class named as PersonalDetail.Step 3Add the lines of codes given below to PersonalDetail class.

Code sample

  1. public class PersonalDetail
  2. public string RegNo { get; set; }
  3. public string Name { get; set; }
  4. public string Address { get; set; }
  5. public string PhoneNo { get; set; }
  6. public DateTime AdmissionDate { get; set; }

Add Web APIStep 1Right click on Controller Folder and Add => Controller.

Step 2Select API Controller – Empty.Step 3Click Add.

Step 4Name the Web API as StudentAPI.

Step 5Now, create [HttpGet] type method called GetAllStudents().

Your method should look, as shown below.

Code sample

  1. public class StudentAPIController : Controller
  2. [HttpGet]
  3. public IEnumerable GetAllStudents()
  4. List students = new List
  5. new PersonalDetail{
  6. RegNo = “2017-0001”,
  7. Name = “Nishan”,
  8. Address = “Kathmandu”,
  9. PhoneNo = “9849845061”,
  10. AdmissionDate = DateTime.Now
  11. },
  12. new PersonalDetail{
  13. RegNo = “2017-0002”,
  14. Name = “Namrata Rai”,
  15. Address = “Bhaktapur”,
  16. PhoneNo = “9849845062”,
  17. AdmissionDate = DateTime.Now
  18. },
  19. };
  20. return students;

Call Web API using Jquery AJAXCreating Controller and View

You can create a new controller and view for displaying the data returned by Web API. For Now I used Index Method of Home Controller to call Web API just created.

Step 1

Open Views => Home => Index.cshtml

Step 2

Lets remove unnecessady HTML codes.

Step 3

Add Reference to Jquery.

Step 4

Let’s add a simple HTML Table to display data returned from Web API in tablular form.

Code sample

  1. //Reference to JQuery
  2. Test Data from API


Regd No


Name


Address


Phone No


Admission Date

Step 5

Let’s add jQuery scripts to call Web API, which we just created and parse the data sent by API to HTML. AJAX looks, as shown below.

Code sample

More about jQuery AJAX

AJAX is a developer’s dream(Defn from W3Schools), because you can

  • Update a Web page without reloading the page.
  • Request data from a server – after the page has loaded.
  • Receive data from a server – after the page has loaded.
  • Send the data to a Server – in the background.

To learn the basics of AJAX, please visit https://www.w3schools.com/xml/ajax_intro.asp

Parts of AJAX

type: GET/POST

url : URL ofWeb API to pull/push data

contentType: application/json

dataType: json

success: function()

failure: function()

error: function()

Application Execution

Now, run the Index Mthod of Home Page Controller and you will be able to retrieve all the data passed from Web API. If you navigate to the Web API, which we just created, it looks as shown below.

Now, let’s navigate to Index Method of Home Contoller (Where we load WebAPI using JQuery AJAX)

JSON data shown above is parsed here.

Checking data, using Browser console

Let’s check the data shown above, using Browser console too. The data in the console looks as shown below.

If you like to show the data only after clicking any buttons, you can customize the script section to load the data.

Summary

I hope you learned:

How to Send API Requests Using jQuery

Learn how to send API requests using jQuery. Discover step-by-step instructions, practical examples, and best practices for making API calls using jQuery.

Unlock the full potential of API communication with jQuery, a versatile JavaScript library renowned for its simplicity and efficiency. In this article, we will explore the intricacies of using jQuery to make API requests, shedding light on its significance, practical implementation, and the role of Apidog in generating streamlined jQuery API request code.

Calling Web API from JavaScript or jQuery [ASP.NET Core Web API]
Calling Web API from JavaScript or jQuery [ASP.NET Core Web API]

Introduction

This is the first “Web API with AJAX” article series presentation. This article provides a basic understanding of the Web API and concepts of AJAX in web applications. We can say that the Web API is the latest communication technology of the Microsoft platform. If we look back at Microsoft’s communication technology, we will find that communication started by holding the hand of remoting techniques. Then the concept of Web Services was introduced, and SOAP messages began to send messages back and forth.

Keywords searched by users: call web api using jquery ajax

Call Asp Net Web Api From Jquery - Youtube
Call Asp Net Web Api From Jquery – Youtube
Call Web Api Using Ajax | Jquery Ajax Method - Youtube
Call Web Api Using Ajax | Jquery Ajax Method – Youtube
How To Call Asp.Net Core Web Api Using Jquery Ajax | Allow Cors Access-Control-Allow-Origin  - Youtube
How To Call Asp.Net Core Web Api Using Jquery Ajax | Allow Cors Access-Control-Allow-Origin – Youtube
Ajax #Jquery #Web #Api Web Api Call Using Jquery Ajax Video Tutorial -  Youtube
Ajax #Jquery #Web #Api Web Api Call Using Jquery Ajax Video Tutorial – Youtube
Mvc Using Web Api And Jquery To Get Or Post Data - Codeproject
Mvc Using Web Api And Jquery To Get Or Post Data – Codeproject
How To Call Web Api From Jquery [Asp.Net Core Edition]
How To Call Web Api From Jquery [Asp.Net Core Edition]
Call (Consume) Web Api Using Jquery Ajax In Asp.Net Mvc - Youtube
Call (Consume) Web Api Using Jquery Ajax In Asp.Net Mvc – Youtube
Github - Sumuongit/Asp-Mvc-Web-Api-Jquery-Ajax-Crud: A Sample Application  On Crud Operation Using Asp.Net Mvc 5, Web Api, Jquery Ajax (For Calling  Web Api), Entity Framework (Code First Approach) And Sql Server 2012
Github – Sumuongit/Asp-Mvc-Web-Api-Jquery-Ajax-Crud: A Sample Application On Crud Operation Using Asp.Net Mvc 5, Web Api, Jquery Ajax (For Calling Web Api), Entity Framework (Code First Approach) And Sql Server 2012
Gọi Web Api Sử Dụng Ajax Jquery
Gọi Web Api Sử Dụng Ajax Jquery
Getting Started With Jquery $.Ajax() – Back To Basics | Dotnetcurry
Getting Started With Jquery $.Ajax() – Back To Basics | Dotnetcurry
Calling Web Api Service In A Cross Domain Using Jquery Ajax
Calling Web Api Service In A Cross Domain Using Jquery Ajax
How Ajax Works? Difference Between Angular Js And Jquery - Geeksforgeeks
How Ajax Works? Difference Between Angular Js And Jquery – Geeksforgeeks
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software  Engineering
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software Engineering
Javascript Ajax Post And Get Method Example
Javascript Ajax Post And Get Method Example

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *