Skip to content
Home » Jquery Call Web Api | Reservation

Jquery Call Web Api | Reservation

Call web api service with basic authentication using jquery ajax

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

Reservation

ID Name Start Location End Location

There are some input controls. The reservation to be updated will first be fetched from the API, and is shown on these input controls.

User will update the reservation by entering the updated values in these input controls, and clicking the button.

On clicking the button the reservation will be updated and the newly updated values are shown inside the HTML table.

Next add the following jQuery code to this page:


$(document).ready(function () { GetReservation(); function GetReservation() { let params = (new URL(document.location)).searchParams; let id = params.get("id"); $.ajax({ url: "https://localhost:44324/api/Reservation/" + id, type: "get", contentType: "application/json", success: function (result, status, xhr) { $("#Id").val(result["id"]); $("#Name").val(result["name"]); $("#StartLocation").val(result["startLocation"]); $("#EndLocation").val(result["endLocation"]); }, error: function (xhr, status, error) { console.log(xhr) } }); } $("#UpdateButton").click(function (e) { let params = (new URL(document.location)).searchParams; let id = params.get("id"); data = new FormData(); data.append("Id", $("#Id").val()); data.append("Name", $("#Name").val()); data.append("StartLocation", $("#StartLocation").val()); data.append("EndLocation", $("#EndLocation").val()); $.ajax({ url: "https://localhost:44324/api/Reservation", type: "put", data: data, processData: false, contentType: false, success: function (result, status, xhr) { var str = "

" + result["id"] + " " + result["name"] + " " + result["startLocation"] + " " + result[ $("table tbody").append(str); $("#resultDiv").show(); }, error: function (xhr, status, error) { console.log(xhr) } }); }); });

The reservation id is send to this page in query string. To get this reservation id the following 2 lines of codes are used:

let params = (new URL(document.location)).searchParams; let id = params.get(“id”);

So the variable called id now has the reservation id.

I then make the Call to the GET Method of the API to fetch the reservation data of this particular id.

Check the URL of the API to see id is added to the end of it.


url: "https://localhost:44324/api/Reservation/" + id

Once I get the reservation data from the Web API I bind it to the input controls:

$(“#Id”).val(result[“id”]); $(“#Name”).val(result[“name”]); $(“#StartLocation”).val(result[“startLocation”]); $(“#EndLocation”).val(result[“endLocation”]);

Now when the UpdateButton is clicked the reservation gets updated. See the jQuery AJAX code which Calls the Web API’s PUT Method.


$.ajax({ url: "https://localhost:44324/api/Reservation", type: "put", data: data, processData: false, contentType: false, success: function (result, status, xhr) { var str = "

" + result["id"] + " " + result["name"] + " " + result["startLocation"] + " " + result[ $("table tbody").append(str); $("#resultDiv").show(); }, error: function (xhr, status, error) { console.log(xhr) } });

Notice that I have put the processData and contentType values to false:

processData: false contentType: false

Also notice the I send the updated reservation data to the Web API PUT method in a FormData object.

data = new FormData(); data.append(“Id”, $(“#Id”).val()); data.append(“Name”, $(“#Name”).val()); data.append(“StartLocation”, $(“#StartLocation”).val()); data.append(“EndLocation”, $(“#EndLocation”).val());

The functionality is shown by the below video:

Now I will Call the HTTP PATCH method of Web API, this method is shown below. Note that the HTTP PATCH method is also used to update a reservation.


[HttpPatch("{id}")] public StatusCodeResult Patch(int id, [FromBody]JsonPatchDocument

patch) { //… }

Create a new HTML page called UpdateReservationPatch.html. Then add the following HTML to this page:

There are input controls where the user can put the updated reservation values, and a button which on clicking will make the Web API call to update the reservation.

Now add the following jQuery code to this page:

$(document).ready(function () { GetReservation(); function GetReservation() { let params = (new URL(document.location)).searchParams; let id = params.get(“id”); $.ajax({ url: “https://localhost:44324/api/Reservation/” + id, type: “get”, contentType: “application/json”, success: function (result, status, xhr) { $(“#Id”).val(result[“id”]); $(“#Name”).val(result[“name”]); $(“#StartLocation”).val(result[“startLocation”]); $(“#EndLocation”).val(result[“endLocation”]); }, error: function (xhr, status, error) { console.log(xhr) } }); } $(“#UpdateButton”).click(function (e) { let params = (new URL(document.location)).searchParams; let id = params.get(“id”); $.ajax({ url: “https://localhost:44324/api/Reservation/” + id, type: “patch”, contentType: “application/json”, data: JSON.stringify([ { op: “replace”, path: “Name”, value: $(“#Name”).val() }, { op: “replace”, path: “StartLocation”, value: $(“#StartLocation”).val() } ]), success: function (result, status, xhr) { window.location.href = “AllReservation.html”; }, error: function (xhr, status, error) { console.log(xhr) } }); }); });

The reservation id is sent to this page’s URL in query string. So the GetReservation() gets this id and fetches it’s data by making the API call with the GET Method.

The HTTP PATCH type of API request is made by the UpdateButton click’s code which is:

$(“#UpdateButton”).click(function (e) { let params = (new URL(document.location)).searchParams; let id = params.get(“id”); $.ajax({ url: “https://localhost:44324/api/Reservation/” + id, type: “patch”, contentType: “application/json”, data: JSON.stringify([ { op: “replace”, path: “Name”, value: $(“#Name”).val() }, { op: “replace”, path: “StartLocation”, value: $(“#StartLocation”).val() } ]), success: function (result, status, xhr) { window.location.href = “AllReservation.html”; }, error: function (xhr, status, error) { console.log(xhr) } }); });

Notice that I used the JSON.stringify() method to send a json to the Web API. This json contains 3 name/value pairs:

data: JSON.stringify([ { op: “replace”, path: “Name”, value: $(“#Name”).val() }, { op: “replace”, path: “StartLocation”, value: $(“#StartLocation”).val() } ])

Go to AllReservation.html page and change the URL for the edit icon to UpdateReservationPatch.html.


appendElement.append($("

").html(""

Then check the functionality which is shown by the below video:

Here I will have to invoke the Web API GET method and pass id parameter to it. This method is shown bwlow.

[HttpGet(“{id}”)] public ActionResult

Get(int id) { if (id == 0) return BadRequest(“Value must be passed in the request body.”); return Ok(repository[id]); }

So, create a new HTML Page called GetReservation.html and add the following code to it:

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

C-Sharpcorner Member List

Now, press F5 to execute the project.

You will encounter the following errors in Developer Tools.

ERROR 1

  1. OPTIONS http://localhost:52044/api/member 405 (Method Not Allowed).
  2. Response to the preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50702' is therefore not allowed access.

To remove the above errors, the Web.Config file needs to be updated.

Update Web.Config file of your WebAPI Project with the following codes.

Now, press F5 to execute the project again.

ERROR 2

  1. OPTIONS http://localhost:52044/api/member 405 (Method Not Allowed)
  1. Failed to load http://localhost:52044/api/member: Response for preflight does not have HTTP ok status.

To remove the above errors, the Global.asax.cs file needs to be updated. Update the Global.asax.cs file of your WebAPI Project with the following codes.

  1. protected void Application_BeginRequest()
  2. if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
  3. Response.End();
  4. Response.Flush();

Now, you can see the developer tools in the output screen. You will get the perfect output in console log.

Now, you can see on the browser that your browser is ready with the following output.

OUTPUT

I am a beginner of ASP MVC with web api.

By using below codes I tried to call a function which is written at the controller. For checking I used breakpoint so the control could not go to the controller so that I can not track actually what is going on.

The given code explains how to pass username and password to the controller:

This is the controller which i used to pass


public class LoginController : ApiController { [HttpPost] public void Login(Login login) { string user = login.UserName.ToString(); string password = login.Password.ToString(); } }

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

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.

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

Reservation

ID Name Start Location End Location

There are 3 input controls for accepting the Name, Start Location and End Location of a new reservation:

There is also a button, on whose click event the API call is made:



Once, the reservation is created then the API will send the new reservation’s data in JSON format. I will show this data in the HTML table which is kept inside the hidden div:

Call the web API with JavaScript

In this section, you’ll add an HTML page containing forms for creating and managing to-do items. Event handlers are attached to elements on the page. The event handlers result in HTTP requests to the web API’s action methods. The Fetch API’s

fetch

function initiates each HTTP request.

The

fetch

function returns a

Promise

object, which contains an HTTP response represented as a

Response

object. A common pattern is to extract the JSON response body by invoking the

json

function on the

Response

object. JavaScript updates the page with the details from the web API’s response.

The simplest

fetch

call accepts a single parameter representing the route. A second parameter, known as the

init

object, is optional.

init

is used to configure the HTTP request.

  1. Configure the app to serve static files and enable default file mapping. The following highlighted code is needed in the


    Configure

    method of

    Startup.cs

    :

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }

  2. Create a wwwroot folder in the project root.

  3. Create a css folder inside of the wwwroot folder.

  4. Create a js folder inside of the wwwroot folder.

  5. Add an HTML file named


    index.html

    to the wwwroot folder. Replace the contents of

    index.html

    with the following markup:

    <br /> To-do CRUD<br />

    To-do CRUD

    Add

    Edit

    Is Complete? Name




  6. Add a CSS file named


    site.css

    to the wwwroot/css folder. Replace the contents of

    site.css

    with the following styles:

    input[type='submit'], button, [aria-label] { cursor: pointer; } #editForm { display: none; } table { font-family: Arial, sans-serif; border: 1px solid; border-collapse: collapse; } th { background-color: #f8f8f8; padding: 5px; } td { border: 1px solid; padding: 5px; }

  7. Add a JavaScript file named


    site.js

    to the wwwroot/js folder. Replace the contents of

    site.js

    with the following code:

    const uri = 'api/todoitems'; let todos = []; function getItems() { fetch(uri) .then(response => response.json()) .then(data => _displayItems(data)) .catch(error => console.error('Unable to get items.', error)); } function addItem() { const addNameTextbox = document.getElementById('add-name'); const item = { isComplete: false, name: addNameTextbox.value.trim() }; fetch(uri, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(response => response.json()) .then(() => { getItems(); addNameTextbox.value = ''; }) .catch(error => console.error('Unable to add item.', error)); } function deleteItem(id) { fetch(`${uri}/${id}`, { method: 'DELETE' }) .then(() => getItems()) .catch(error => console.error('Unable to delete item.', error)); } function displayEditForm(id) { const item = todos.find(item => item.id === id); document.getElementById('edit-name').value = item.name; document.getElementById('edit-id').value = item.id; document.getElementById('edit-isComplete').checked = item.isComplete; document.getElementById('editForm').style.display = 'block'; } function updateItem() { const itemId = document.getElementById('edit-id').value; const item = { id: parseInt(itemId, 10), isComplete: document.getElementById('edit-isComplete').checked, name: document.getElementById('edit-name').value.trim() }; fetch(`${uri}/${itemId}`, { method: 'PUT', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(() => getItems()) .catch(error => console.error('Unable to update item.', error)); closeInput(); return false; } function closeInput() { document.getElementById('editForm').style.display = 'none'; } function _displayCount(itemCount) { const name = (itemCount === 1) ? 'to-do' : 'to-dos'; document.getElementById('counter').innerText = `${itemCount} ${name}`; } function _displayItems(data) { const tBody = document.getElementById('todos'); tBody.innerHTML = ''; _displayCount(data.length); const button = document.createElement('button'); data.forEach(item => { let isCompleteCheckbox = document.createElement('input'); isCompleteCheckbox.type = 'checkbox'; isCompleteCheckbox.disabled = true; isCompleteCheckbox.checked = item.isComplete; let editButton = button.cloneNode(false); editButton.innerText = 'Edit'; editButton.setAttribute('onclick', `displayEditForm(${item.id})`); let deleteButton = button.cloneNode(false); deleteButton.innerText = 'Delete'; deleteButton.setAttribute('onclick', `deleteItem(${item.id})`); let tr = tBody.insertRow(); let td1 = tr.insertCell(0); td1.appendChild(isCompleteCheckbox); let td2 = tr.insertCell(1); let textNode = document.createTextNode(item.name); td2.appendChild(textNode); let td3 = tr.insertCell(2); td3.appendChild(editButton); let td4 = tr.insertCell(3); td4.appendChild(deleteButton); }); todos = data; }

A change to the ASP.NET Core project’s launch settings may be required to test the HTML page locally:

  1. Open Properties\launchSettings.json.
  2. Remove the

    launchUrl

    property to force the app to open at

    index.html

    —the project’s default file.

This sample calls all of the CRUD methods of the web API. Following are explanations of the web API requests.

Get a list of to-do items

In the following code, an HTTP GET request is sent to the api/todoitems route:


fetch(uri) .then(response => response.json()) .then(data => _displayItems(data)) .catch(error => console.error('Unable to get items.', error));

When the web API returns a successful status code, the

_displayItems

function is invoked. Each to-do item in the array parameter accepted by

_displayItems

is added to a table with Edit and Delete buttons. If the web API request fails, an error is logged to the browser’s console.

Add a to-do item

In the following code:

  • An

    item

    variable is declared to construct an object literal representation of the to-do item.
  • A Fetch request is configured with the following options:


    • method

      —specifies the POST HTTP action verb.

    • body

      —specifies the JSON representation of the request body. The JSON is produced by passing the object literal stored in

      item

      to the JSON.stringify function.

    • headers

      —specifies the

      Accept

      and

      Content-Type

      HTTP request headers. Both headers are set to

      application/json

      to specify the media type being received and sent, respectively.
  • An HTTP POST request is sent to the api/todoitems route.


function addItem() { const addNameTextbox = document.getElementById('add-name'); const item = { isComplete: false, name: addNameTextbox.value.trim() }; fetch(uri, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(response => response.json()) .then(() => { getItems(); addNameTextbox.value = ''; }) .catch(error => console.error('Unable to add item.', error)); }

When the web API returns a successful status code, the

getItems

function is invoked to update the HTML table. If the web API request fails, an error is logged to the browser’s console.

Update a to-do item

Updating a to-do item is similar to adding one; however, there are two significant differences:

  • The route is suffixed with the unique identifier of the item to update. For example, api/todoitems/1.
  • The HTTP action verb is PUT, as indicated by the

    method

    option.


fetch(`${uri}/${itemId}`, { method: 'PUT', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(() => getItems()) .catch(error => console.error('Unable to update item.', error));

Delete a to-do item

To delete a to-do item, set the request’s

method

option to

DELETE

and specify the item’s unique identifier in the URL.


fetch(`${uri}/${id}`, { method: 'DELETE' }) .then(() => getItems()) .catch(error => console.error('Unable to delete item.', error));

Advance to the next tutorial to learn how to generate web API help pages:

This tutorial shows how to call an ASP.NET Core web API with JavaScript, using the Fetch API.

Call ASP NET Web API from jQuery
Call ASP NET Web API from jQuery

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.”)

%>

Step 1

Open Visual Studio 2017 and select “File” -> “New” -> “Project.”

In the Template Project Window, select Visual C# >ASP.NET Web Application and then select “Web API.” Change the name of the project to “MyWebAPI” and click the “OK” button (see Figures 1 and 2).

Figure 1: Creating a new Web API Project

Figure 2: Selecting a Web API Template

Step 2

We have to add a new model now. The Web API Model can be serialized automatically in JavaScript Object Notation (JSON) and Extensible Markup Language (XML) format. We can use the model to represent the data in our application.

To add a new model in the application, go to the Solution Explorer and right-click the “Model” folder. From the context menu, select “Add” and select the class. Name the class Employee.cs, as shown in Figure 3.

Figure 3: Adding a new Model in the Project

Step 3

Add the following code in the Employee class. I have created an employee and employee details classes.

using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TestWebAPIProj.Models { public class Employee { public string EmployeeName { get; set; } public EmployeeDetails empdetails { get; set; } } public class EmployeeDetails { public string email { get; set; } public int age { get; set; } public double salary { get; set; } public string department { get; set; } public int totalexp { get; set; } } }

Step 4

Next, add a Controller. The Controller handles the HTTP requests. To add a new Controller, go to the Solution Explorer and right-click the “Controller” folder. Select “Add and Select Controller”. Change the name of the controller to “EmployeeController” (see Figure 4).

Figure 4: Adding a new Controller in the Project

From the Template, select “Web API 2 Controller – Empty”, as shown in Figure 5.

Figure 5: Selecting a Web API Controller Template

Step 5

My controller inherits the ApiController class and exposes two API methods. Now add the following code to the Employee Controller.

using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using TestWebAPIProj.Models; using System.Web.Script.Serialization; namespace TestWebAPIProj.Controllers { public class EmployeeController : ApiController { public string GetEmpInfo(string JSONString) { var seriptSerialization = new System.Web.Script .Serialization.JavaScriptSerializer(); Employee employee = seriptSerialization .Deserialize

(JSONString); return “EmployeeName – ” + employee.EmployeeName + “Employee Age- ” + employee.empdetails.age + “Employee Dept – ” + employee.empdetails.department + “Employee Email – ” + employee.empdetails.email + “Employee Salary – ” + employee.empdetails.salary + “Employee Experience – ” + employee.empdetails.totalexp ; } public string SubmitEmpdata([FromBody]Employee emp) { return “EmployeeName – ” + emp.EmployeeName + “Employee Age – ” + emp.empdetails.age + “Employee Dept – ” + emp.empdetails.department + “Employee Email – ” + emp.empdetails.email + “Employee Salary – ” + emp.empdetails.salary + “Employee Experience – ” + emp.empdetails.totalexp; } } }

Step 6

Next, I have added the following route in the WebApiConfig.cs file present in App_Start folder.

public static void Register(HttpConfiguration config) { // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter (OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: “DefaultApi”, routeTemplate: “api/{controller}/{action}/{id}”, defaults: new { id = RouteParameter.Optional } ); }

Step 7

We have to add client-side HTML code now and consume the Web API created in the previous step. In the Solution Explorer, expand the Home Folder and double-click Index.cshtml (see Figure 6).

Figure 6: Updating the Index.chtml view with HTML Code

Add the following code in the Index.cshtml page. I have called the GetEmpInfo () and SubmitEmpdata () API functions from JavaScript code. Now, execute the application to see the output.

<br /> ASP.NET Web API Sample<br />



Get Employee


Post Employee

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

Call the web API with JavaScript

In this section, you’ll add an HTML page containing forms for creating and managing to-do items. Event handlers are attached to elements on the page. The event handlers result in HTTP requests to the web API’s action methods. The Fetch API’s

fetch

function initiates each HTTP request.

The

fetch

function returns a

Promise

object, which contains an HTTP response represented as a

Response

object. A common pattern is to extract the JSON response body by invoking the

json

function on the

Response

object. JavaScript updates the page with the details from the web API’s response.

The simplest

fetch

call accepts a single parameter representing the route. A second parameter, known as the

init

object, is optional.

init

is used to configure the HTTP request.

  1. Configure the app to serve static files and enable default file mapping. The following highlighted code is needed in

    Program.cs

    :


using Microsoft.EntityFrameworkCore; using TodoApi.Models; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddDbContext

(opt => opt.UseInMemoryDatabase("TodoList")); var app = builder.Build(); if (builder.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();

  1. Create a wwwroot folder in the project root.

  2. Create a css folder inside of the wwwroot folder.

  3. Create a js folder inside of the wwwroot folder.

  4. Add an HTML file named


    index.html

    to the wwwroot folder. Replace the contents of

    index.html

    with the following markup:

    <br /> To-do CRUD<br />

    To-do CRUD

    Add

    Edit

    Is Complete? Name




  5. Add a CSS file named


    site.css

    to the wwwroot/css folder. Replace the contents of

    site.css

    with the following styles:

    input[type='submit'], button, [aria-label] { cursor: pointer; } #editForm { display: none; } table { font-family: Arial, sans-serif; border: 1px solid; border-collapse: collapse; } th { background-color: #f8f8f8; padding: 5px; } td { border: 1px solid; padding: 5px; }

  6. Add a JavaScript file named


    site.js

    to the wwwroot/js folder. Replace the contents of

    site.js

    with the following code:

    const uri = 'api/todoitems'; let todos = []; function getItems() { fetch(uri) .then(response => response.json()) .then(data => _displayItems(data)) .catch(error => console.error('Unable to get items.', error)); } function addItem() { const addNameTextbox = document.getElementById('add-name'); const item = { isComplete: false, name: addNameTextbox.value.trim() }; fetch(uri, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(response => response.json()) .then(() => { getItems(); addNameTextbox.value = ''; }) .catch(error => console.error('Unable to add item.', error)); } function deleteItem(id) { fetch(`${uri}/${id}`, { method: 'DELETE' }) .then(() => getItems()) .catch(error => console.error('Unable to delete item.', error)); } function displayEditForm(id) { const item = todos.find(item => item.id === id); document.getElementById('edit-name').value = item.name; document.getElementById('edit-id').value = item.id; document.getElementById('edit-isComplete').checked = item.isComplete; document.getElementById('editForm').style.display = 'block'; } function updateItem() { const itemId = document.getElementById('edit-id').value; const item = { id: parseInt(itemId, 10), isComplete: document.getElementById('edit-isComplete').checked, name: document.getElementById('edit-name').value.trim() }; fetch(`${uri}/${itemId}`, { method: 'PUT', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(() => getItems()) .catch(error => console.error('Unable to update item.', error)); closeInput(); return false; } function closeInput() { document.getElementById('editForm').style.display = 'none'; } function _displayCount(itemCount) { const name = (itemCount === 1) ? 'to-do' : 'to-dos'; document.getElementById('counter').innerText = `${itemCount} ${name}`; } function _displayItems(data) { const tBody = document.getElementById('todos'); tBody.innerHTML = ''; _displayCount(data.length); const button = document.createElement('button'); data.forEach(item => { let isCompleteCheckbox = document.createElement('input'); isCompleteCheckbox.type = 'checkbox'; isCompleteCheckbox.disabled = true; isCompleteCheckbox.checked = item.isComplete; let editButton = button.cloneNode(false); editButton.innerText = 'Edit'; editButton.setAttribute('onclick', `displayEditForm(${item.id})`); let deleteButton = button.cloneNode(false); deleteButton.innerText = 'Delete'; deleteButton.setAttribute('onclick', `deleteItem(${item.id})`); let tr = tBody.insertRow(); let td1 = tr.insertCell(0); td1.appendChild(isCompleteCheckbox); let td2 = tr.insertCell(1); let textNode = document.createTextNode(item.name); td2.appendChild(textNode); let td3 = tr.insertCell(2); td3.appendChild(editButton); let td4 = tr.insertCell(3); td4.appendChild(deleteButton); }); todos = data; }

A change to the ASP.NET Core project’s launch settings may be required to test the HTML page locally:

  1. Open Properties\launchSettings.json.
  2. Remove the

    launchUrl

    property to force the app to open at

    index.html

    —the project’s default file.

This sample calls all of the CRUD methods of the web API. Following are explanations of the web API requests.

Get a list of to-do items

In the following code, an HTTP GET request is sent to the api/todoitems route:


fetch(uri) .then(response => response.json()) .then(data => _displayItems(data)) .catch(error => console.error('Unable to get items.', error));

When the web API returns a successful status code, the

_displayItems

function is invoked. Each to-do item in the array parameter accepted by

_displayItems

is added to a table with Edit and Delete buttons. If the web API request fails, an error is logged to the browser’s console.

Add a to-do item

In the following code:

  • An

    item

    variable is declared to construct an object literal representation of the to-do item.
  • A Fetch request is configured with the following options:


    • method

      —specifies the POST HTTP action verb.

    • body

      —specifies the JSON representation of the request body. The JSON is produced by passing the object literal stored in

      item

      to the JSON.stringify function.

    • headers

      —specifies the

      Accept

      and

      Content-Type

      HTTP request headers. Both headers are set to

      application/json

      to specify the media type being received and sent, respectively.
  • An HTTP POST request is sent to the api/todoitems route.


function addItem() { const addNameTextbox = document.getElementById('add-name'); const item = { isComplete: false, name: addNameTextbox.value.trim() }; fetch(uri, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(response => response.json()) .then(() => { getItems(); addNameTextbox.value = ''; }) .catch(error => console.error('Unable to add item.', error)); }

When the web API returns a successful status code, the

getItems

function is invoked to update the HTML table. If the web API request fails, an error is logged to the browser’s console.

Update a to-do item

Updating a to-do item is similar to adding one; however, there are two significant differences:

  • The route is suffixed with the unique identifier of the item to update. For example, api/todoitems/1.
  • The HTTP action verb is PUT, as indicated by the

    method

    option.


fetch(`${uri}/${itemId}`, { method: 'PUT', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(() => getItems()) .catch(error => console.error('Unable to update item.', error));

Delete a to-do item

To delete a to-do item, set the request’s

method

option to

DELETE

and specify the item’s unique identifier in the URL.


fetch(`${uri}/${id}`, { method: 'DELETE' }) .then(() => getItems()) .catch(error => console.error('Unable to delete item.', error));

Advance to the next tutorial to learn how to generate web API help pages:

This tutorial shows how to call an ASP.NET Core web API with JavaScript, using the Fetch API.

C-Sharpcorner Member List

Now, press F5 to execute the project.

You will encounter the following errors in Developer Tools.

ERROR 1

  1. OPTIONS http://localhost:52044/api/member 405 (Method Not Allowed).
  2. Response to the preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:50702’ is therefore not allowed access.

To remove the above errors, the Web.Config file needs to be updated.

Update Web.Config file of your WebAPI Project with the following codes.

Now, press F5 to execute the project again.

ERROR 2

  1. OPTIONS http://localhost:52044/api/member 405 (Method Not Allowed)
  1. Failed to load http://localhost:52044/api/member: Response for preflight does not have HTTP ok status.

To remove the above errors, the Global.asax.cs file needs to be updated. Update the Global.asax.cs file of your WebAPI Project with the following codes.

  1. protected void Application_BeginRequest()
  2. if (Request.Headers.AllKeys.Contains(“Origin”) && Request.HttpMethod == “OPTIONS”)
  3. Response.End();
  4. Response.Flush();

Now, you can see the developer tools in the output screen. You will get the perfect output in console log.

Now, you can see on the browser that your browser is ready with the following output.

OUTPUT

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.

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

Call the web API with JavaScript

In this section, you’ll add an HTML page containing forms for creating and managing to-do items. Event handlers are attached to elements on the page. The event handlers result in HTTP requests to the web API’s action methods. The Fetch API’s

fetch

function initiates each HTTP request.

The

fetch

function returns a

Promise

object, which contains an HTTP response represented as a

Response

object. A common pattern is to extract the JSON response body by invoking the

json

function on the

Response

object. JavaScript updates the page with the details from the web API’s response.

The simplest

fetch

call accepts a single parameter representing the route. A second parameter, known as the

init

object, is optional.

init

is used to configure the HTTP request.

  1. Configure the app to serve static files and enable default file mapping. The following highlighted code is needed in

    Program.cs

    :


using Microsoft.EntityFrameworkCore; using TodoApi.Models; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddDbContext

(opt => opt.UseInMemoryDatabase("TodoList")); var app = builder.Build(); if (builder.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();

  1. Create a wwwroot folder in the project root.

  2. Create a css folder inside of the wwwroot folder.

  3. Create a js folder inside of the wwwroot folder.

  4. Add an HTML file named


    index.html

    to the wwwroot folder. Replace the contents of

    index.html

    with the following markup:

    <br /> To-do CRUD<br />

    To-do CRUD

    Add

    Edit

    Is Complete? Name




  5. Add a CSS file named


    site.css

    to the wwwroot/css folder. Replace the contents of

    site.css

    with the following styles:

    input[type='submit'], button, [aria-label] { cursor: pointer; } #editForm { display: none; } table { font-family: Arial, sans-serif; border: 1px solid; border-collapse: collapse; } th { background-color: #f8f8f8; padding: 5px; } td { border: 1px solid; padding: 5px; }

  6. Add a JavaScript file named


    site.js

    to the wwwroot/js folder. Replace the contents of

    site.js

    with the following code:

    const uri = 'api/todoitems'; let todos = []; function getItems() { fetch(uri) .then(response => response.json()) .then(data => _displayItems(data)) .catch(error => console.error('Unable to get items.', error)); } function addItem() { const addNameTextbox = document.getElementById('add-name'); const item = { isComplete: false, name: addNameTextbox.value.trim() }; fetch(uri, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(response => response.json()) .then(() => { getItems(); addNameTextbox.value = ''; }) .catch(error => console.error('Unable to add item.', error)); } function deleteItem(id) { fetch(`${uri}/${id}`, { method: 'DELETE' }) .then(() => getItems()) .catch(error => console.error('Unable to delete item.', error)); } function displayEditForm(id) { const item = todos.find(item => item.id === id); document.getElementById('edit-name').value = item.name; document.getElementById('edit-id').value = item.id; document.getElementById('edit-isComplete').checked = item.isComplete; document.getElementById('editForm').style.display = 'block'; } function updateItem() { const itemId = document.getElementById('edit-id').value; const item = { id: parseInt(itemId, 10), isComplete: document.getElementById('edit-isComplete').checked, name: document.getElementById('edit-name').value.trim() }; fetch(`${uri}/${itemId}`, { method: 'PUT', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(() => getItems()) .catch(error => console.error('Unable to update item.', error)); closeInput(); return false; } function closeInput() { document.getElementById('editForm').style.display = 'none'; } function _displayCount(itemCount) { const name = (itemCount === 1) ? 'to-do' : 'to-dos'; document.getElementById('counter').innerText = `${itemCount} ${name}`; } function _displayItems(data) { const tBody = document.getElementById('todos'); tBody.innerHTML = ''; _displayCount(data.length); const button = document.createElement('button'); data.forEach(item => { let isCompleteCheckbox = document.createElement('input'); isCompleteCheckbox.type = 'checkbox'; isCompleteCheckbox.disabled = true; isCompleteCheckbox.checked = item.isComplete; let editButton = button.cloneNode(false); editButton.innerText = 'Edit'; editButton.setAttribute('onclick', `displayEditForm(${item.id})`); let deleteButton = button.cloneNode(false); deleteButton.innerText = 'Delete'; deleteButton.setAttribute('onclick', `deleteItem(${item.id})`); let tr = tBody.insertRow(); let td1 = tr.insertCell(0); td1.appendChild(isCompleteCheckbox); let td2 = tr.insertCell(1); let textNode = document.createTextNode(item.name); td2.appendChild(textNode); let td3 = tr.insertCell(2); td3.appendChild(editButton); let td4 = tr.insertCell(3); td4.appendChild(deleteButton); }); todos = data; }

A change to the ASP.NET Core project’s launch settings may be required to test the HTML page locally:

  1. Open Properties\launchSettings.json.
  2. Remove the

    launchUrl

    property to force the app to open at

    index.html

    —the project’s default file.

This sample calls all of the CRUD methods of the web API. Following are explanations of the web API requests.

Get a list of to-do items

In the following code, an HTTP GET request is sent to the api/todoitems route:


fetch(uri) .then(response => response.json()) .then(data => _displayItems(data)) .catch(error => console.error('Unable to get items.', error));

When the web API returns a successful status code, the

_displayItems

function is invoked. Each to-do item in the array parameter accepted by

_displayItems

is added to a table with Edit and Delete buttons. If the web API request fails, an error is logged to the browser’s console.

Add a to-do item

In the following code:

  • An

    item

    variable is declared to construct an object literal representation of the to-do item.
  • A Fetch request is configured with the following options:


    • method

      —specifies the POST HTTP action verb.

    • body

      —specifies the JSON representation of the request body. The JSON is produced by passing the object literal stored in

      item

      to the JSON.stringify function.

    • headers

      —specifies the

      Accept

      and

      Content-Type

      HTTP request headers. Both headers are set to

      application/json

      to specify the media type being received and sent, respectively.
  • An HTTP POST request is sent to the api/todoitems route.


function addItem() { const addNameTextbox = document.getElementById('add-name'); const item = { isComplete: false, name: addNameTextbox.value.trim() }; fetch(uri, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(response => response.json()) .then(() => { getItems(); addNameTextbox.value = ''; }) .catch(error => console.error('Unable to add item.', error)); }

When the web API returns a successful status code, the

getItems

function is invoked to update the HTML table. If the web API request fails, an error is logged to the browser’s console.

Update a to-do item

Updating a to-do item is similar to adding one; however, there are two significant differences:

  • The route is suffixed with the unique identifier of the item to update. For example, api/todoitems/1.
  • The HTTP action verb is PUT, as indicated by the

    method

    option.


fetch(`${uri}/${itemId}`, { method: 'PUT', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }) .then(() => getItems()) .catch(error => console.error('Unable to update item.', error));

Delete a to-do item

To delete a to-do item, set the request’s

method

option to

DELETE

and specify the item’s unique identifier in the URL.


fetch(`${uri}/${id}`, { method: 'DELETE' }) .then(() => getItems()) .catch(error => console.error('Unable to delete item.', error));

Advance to the next tutorial to learn how to generate web API help pages:

Reservation

ID Name Start Location End Location

There is an input control where users will enter the reservation id and a button which on clicking will fetch the reservation’s id data from the API.

There is also a table element which will show the fetched data of the reservation.

Next, add the following jQuery code to this page:


$(document).ready(function () { $("#GetButton").click(function (e) { $("table tbody").html(""); $.ajax({ url: "https://localhost:44324/api/Reservation/" + $("#Id").val(), type: "get", contentType: "application/json", success: function (result, status, xhr) { $("#resultDiv").show(); if (typeof result !== 'undefined') { var str = "

" + result["id"] + " " + result["name"] + " " + result["startLocation"] + " " + result[ $("table tbody").append(str); } else $("table tbody").append("

No Reservation

"); }, error: function (xhr, status, error) { console.log(xhr) } }); }); });

Important thing to note is the id value is added to the URL of the API:


url: "https://localhost:44324/api/Reservation/" + $("#Id").val()

Once I received the value from the API I then show it inside the HTML table. Check the code inside the success callback method which does this work.

Open the page in the browser and enter 2 in the text box and click the button. You will soon get the reservation data for the 2nd reservation object.

Check the below video:

Now I will show how to Upload Image Files to the Web API with jQuery. Here I will have to invoke the following Web API method:


[HttpPost("UploadFile")] public async Task

UploadFile([FromForm] IFormFile file) { //… }

Start by creating an HTML page called AddFile.html and add the following code to it.


Back

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

Uploaded File

There is an input element of type file that will be used to upload an image file to the API. Once the file is uploaded I will show it inside the img tag.

Next, add the following jQuery code to this page:

$(document).ready(function () { $(“#AddButton”).click(function (e) { data = new FormData(); data.append(“file”, $(“#File”)[0].files[0]); $.ajax({ url: “https://localhost:44324/api/Reservation/UploadFile”, type: “post”, data: data, processData: false, contentType: false, success: function (result, status, xhr) { $(“#fileImg”).attr(“src”, result); $(“#fileDiv”).show(); }, error: function (xhr, status, error) { console.log(xhr) } }); }); });

The file is added to the FormData object like:

data = new FormData(); data.append(“file”, $(“#File”)[0].files[0]);

And then I make the HTTP POST type call to the Web API, the URL is – https://localhost:44324/api/Reservation/UploadFile.

Once the image is uploaded to the API server, I show it inside the img tag. I do this inside the success callback of jQuery AJAX method:

success: function (result, status, xhr) { $(“#fileImg”).attr(“src”, result); }

Open the page in the browser and upload an image to the API just like what is shown by the video:

The link to download the full source code of this tutorial is given below:

This Web API tutorial gives you all the working knowledge of calling/consuming any Web API from jQuery. Download the source codes and use it freely in your website.

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:

jQuery AJAX Reference

For a complete overview of all jQuery AJAX methods, please go to our jQuery AJAX Reference.

How to use simple API using AJAX ?

AJAX (Asynchronous JavaScript and XML) is a set of tools used to make calls to the server to fetch some data. In this article, we will see how to implement a simple API call using AJAX. Prerequisites: Basic knowledge of AJAX and its function. You can learn all the basics from here. What are basic building? We will be fetching employee’s names from an employee object from a free API and displaying them inside a list. There are many API available for free on the internet. You can use any one of them. HTML Code: We have a button and to fetch data and an empty unordered list inside which we will be adding our list-items dynamically using JavaScript.

AJAX Code:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Last Updated :
15 Jul, 2022

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Tutorial: Call an ASP.NET Core web API with JavaScript

This tutorial shows how to call an ASP.NET Core web API with JavaScript, using the Fetch API.

.NET Core MVC CRUD  using .NET Core Web API and ajax call | Consume secured  .NET Core API in MVC
.NET Core MVC CRUD using .NET Core Web API and ajax call | Consume secured .NET Core API in MVC

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.

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

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

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

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

.AllowAnyHeader()

.AllowAnyMethod();});});

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

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

.WithHeaders(“Authorize”);

app.UseCors(“AllowOrigin”);

[EnableCors(“AllowOrigin”)]

public class ProductsController : ControllerBase

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

$.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

Introduction

In this article, I will demonstrate how to create a Web API using the ASP.NET MVC framework and consume it from a client application. Web API is new version of Microsoft’s service-oriented application built on top of MVC architecture. Web API is a great framework for exposing your data and service. It can be consumed by a broad range of clients, including browsers, mobiles, iPhone, and tablets. Web API supports conventional CRUD actions. It also supports MVC features such as routing, controllers, action results, filter, model binders, IOC container, and dependency injection; that makes it more simple and robust.

Ngobrolin Open Source - Ngobrolin WEB
Ngobrolin Open Source – Ngobrolin WEB

In this article, you will learn how to consume/use Web API in ASP.NET MVC step by step.

This article is the third part of my ASP.NET MVC Web API series.

Consuming Web API From jQuery

In this article, we have used localhost Web API and called for the GET request. The following is the process:

  • Create ASP.NET MVC Project.
  • Add an HTML file called Members.html file.
  • Write GET call of for jQuery AJAX to fetch the data from ASP.NET Web API.
  • System or process will throw two different errors.
  • Resolve the errors with the solution given in this article.
  • Run the project and check the output.

Step by Step Implementation

Create an new ASP.NET Empty Website project called “ConsumeWebApiFromJquery”.

By default, the Solution Explorer looks like this.

Now, right-click on the project titled “ConsumeWebApiFromJquery” and select ADD –> ADD NEW ITEM –> HTML Page. Give the page a name as “Members.html”.

Switch to Members.html file and add the following code.

  1. Conclusion

    Reading this article, you learned about Web APIs and how to consume them from a Web page. ASP.NET Web API is a framework that makes it easy to build HTTP services, and it’s an ideal platform for building RESTful applications on the .NET Framework.

In my ASP.NET Core tutorial on Web API I created a REST Web API having GET, POST, PUT and DELETE methods. This API was performing CRUD operations on Reservation objects. Now in this tutorial I will Call this Web API from jQuery. I will use jQuery AJAX to pass Parameters and Credentials to the Web API. So let’s get started.

Make sure to keep the Web API project in running state so that the API can be called by jQuery code.

This tutorial is a part of the ASP.NET Core Web API series which contains 5 tutorials to master this area:

Page Contents

The Web API GET method returns all the Reservations. This method is shown below:


[HttpGet] public IEnumerable

Get() { //… }

Now let us Call this Web API GET Method from jQuery. So, create an HTML page called AllReservation.html where all the reservations will be shown. These Reservations will be provided by the Web API and then will be shown in an HTML table.

In this html page create a table as shown below:

ID Name Start Location End Location Update Delete

Notice I specifically kept the tbody element empty. This is because by using jQuery I will show the reservations inside it.

Next, add the following jQuery AJAX Code to the page:

$(document).ready(function () { ShowAllReservation(); function ShowAllReservation() { $(“table tbody”).html(“”); $.ajax({ url: “https://localhost:44324/api/Reservation”, type: “get”, contentType: “application/json”, success: function (result, status, xhr) { $.each(result, function (index, value) { $(“tbody”).append($(”

“)); appendElement = $(“tbody tr”).last(); appendElement.append($(”

“).html(value[“id”])); appendElement.append($(”

“).html(value[“name”])); appendElement.append($(”

“).html(value[“startLocation”])); appendElement.append($(”

“).html(value[“endLocation”])); appendElement.append($(”

“).html(“” appendElement.append($(”

“).html(“”)); }); }, error: function (xhr, status, error) { console.log(xhr) } }); } $(“table”).on(“click”, “img.delete”, function () { var reservationId = $(this).parents(“tr”).find(“td:nth-child(1)”).text(); $.ajax({ url: “https://localhost:44324/api/Reservation/” + reservationId, type: “delete”, contentType: “application/json”, success: function (result, status, xhr) { ShowAllReservation(); }, error: function (xhr, status, error) { console.log(xhr) } }); }); });

I created a JavaScript function called ShowAllReservation() which contain the jQuery .ajax() method. With this AJAX method the Web API is consumed.

Notice I am making an HTTP GET type AJAX Request to the GET method of the Web API whose URL is https://localhost:44324/api/Reservation.

The reservations are send by the API in JSON and they look like:

[ { “id”: 1, “name”: “Ankit”, “startLocation”: “New York”, “endLocation”: “Beijing” }, { “id”: 2, “name”: “Bobby”, “startLocation”: “New Jersey”, “endLocation”: “Boston” }, { “id”: 3, “name”: “Jacky”, “startLocation”: “London”, “endLocation”: “Paris” } ]

Next, check the success callback of the .ajax() method, where I loop through this JSON (with .each method) and showing the values inside the tbody element of the table.

I also added an anchor and an img elements for performing the update and delete actions on the reservations. You will see this in just a moment.

$.each(result, function (index, value) { $(“tbody”).append($(”

“)); appendElement = $(“tbody tr”).last(); appendElement.append($(”

“).html(value[“id”])); appendElement.append($(”

“).html(value[“name”])); appendElement.append($(”

“).html(value[“startLocation”])); appendElement.append($(”

“).html(value[“endLocation”])); appendElement.append($(”

“).html(“” appendElement.append($(”

“).html(“”)); });

Double click the AllReservation.html file to open it in your browser. It will show all the reservation fetched from the Web API and displayed on the table. Check the below image:

The Web API Delete method is:


[HttpDelete("{id}")] public void Delete(int id) => repository.DeleteReservation(id);

To the same AllReservation.html file I also created a click event for the img tag that has a delete class. Then inside this event I will make a Call to the Web API Delete method and this will delete a particular reservation. The code which does this work is given below:

$(“table”).on(“click”, “img.delete”, function () { var reservationId = $(this).parents(“tr”).find(“td:nth-child(1)”).text(); $.ajax({ url: “https://localhost:44324/api/Reservation/” + reservationId, type: “delete”, contentType: “application/json”, success: function (result, status, xhr) { ShowAllReservation(); }, error: function (xhr, status, error) { console.log(xhr) } }); });

I created the click event using jQuery .on() method for the img tag that has a delete class. This is because the img tag is created dynamically.

The first td element of any row gives the reservation id, which I get from the below code:


var reservationId = $(this).parents("tr").find("td:nth-child(1)").text();

After that I Call Web API from jQuery to the DELETE method, this call also contains the reservation id added to the url at the last segment.


url: "https://localhost:44324/api/Reservation/" + reservationId

Once the reservation gets deleted, the ShowAllReservation() function is called in the success callback of jQuery Ajax, and this updates the table.

Click the cross icon against any reservation object and the API will delete it. Check the below video which shows the delete process:

The Web API POST method has the task of creating new reservations which it receives in it’s parameter. It’s skeleton is shown below.


[HttpPost] public IActionResult Post([FromBody] Reservation res) { //… }

Now I will Call the POST method of Web API from jQuery by passing the reservation on it’s parameter. This means the new Reservation is send in JSON to the Web API. So, create a new HTML page called AddReservation.html and add the following html code to it.

Calling the Web API with Javascript and jQuery

In this task, you will see how to call the Web API programmatically by using Javascript and jQuery. You will invoke the custom GetCarsByMake method and display the list of cars in Kendo UI grid.

Adding Kendo UI in Your Project

The first step is to add Kendo UI in your project. To do this:

  1. Open the Package Manager Console (Tools > Library Package Manager > Package Manager Console).
  2. Add KendoUI to the project using the command: Install-Package KendoUIWeb. Once you run the NuGet command, the Solution Explorer should look like this:

Defining Sample User Interface and Calling the Web API

Next, you will create a sample HTML page that will be used for searching of cars and displaying the result:

  1. Add a new HTML page named SearchForCarsPage.html in the SofiaCarRentalWebApp project.

  2. You will see how a client can access Web API using plain HTML and Javascript. Go ahead and replace the content of SearchForCarsPage.html with the following:

    Note that you will need to adjust the script to match the version of Kendo UI installed by the Package Manager Console.


    <br /> ASP.NET Web API<br />

    # Search for Cars #



    The web page contains an input control and a button. When you enter a make and click the Search button, all concrete cars will be loaded and displayed in a Kendo Grid.

  3. The js function find() is the place where you will call the custom GetCarsByMake method. Basically, you need to define a new Kendo DataSource. The DataSource component is an abstraction for using local or remote (XML, JSON, JSONP) data. It fully supports CRUD data operations and provides both local and server-side support for sorting, paging and filtering. You need to set the read url to the custom action method. The second step is to initialize a new Kendo Grid and set the data source. The complete Javascript for the find() function is listed below:


    function find() { var make = $('#carMake').val(); var carsDataSource = new kendo.data.DataSource( { transport: { read: { url: "/api/cars/?Make=" + make, dataType: "json" } } }); $("#grid").kendoGrid({ dataSource: carsDataSource, columns: [ { field: "CarID", title: "Id" }, { field: "Make", title: "Make" }, { field: "Model", title: "Model" }, { field: "CarYear", title: "Year" } ] }); }

  4. To test the HTML page, right-click SearchForCarsPage.html in Solution Explorer and select View in Browser. Enter a Make in the text box and click Search.

In the next several tutorials, you see how to perform CRUD operations. First, you will add a new page for reading and displaying all categories.

In this article, you will learn how to consume/use Web API in ASP.NET MVC step by step.

This article is the third part of my ASP.NET MVC Web API series.

Consuming Web API From jQuery

In this article, we have used localhost Web API and called for the GET request. The following is the process:

  • Create ASP.NET MVC Project.
  • Add an HTML file called Members.html file.
  • Write GET call of for jQuery AJAX to fetch the data from ASP.NET Web API.
  • System or process will throw two different errors.
  • Resolve the errors with the solution given in this article.
  • Run the project and check the output.

Step by Step Implementation

Create an new ASP.NET Empty Website project called “ConsumeWebApiFromJquery”.

By default, the Solution Explorer looks like this.

Now, right-click on the project titled “ConsumeWebApiFromJquery” and select ADD --> ADD NEW ITEM --> HTML Page. Give the page a name as “Members.html”.

Switch to Members.html file and add the following code.

  1. How to Call External API in C#
    How to Call External API in C#

    Reservation

    ID Name Start Location End Location

Next, add the following jQuery code to this page:


$("#AddButton").click(function (e) { $.ajax({ url: "https://localhost:44324/api/Reservation", headers: { Key: "Secret@123" }, type: "post", contentType: "application/json", data: JSON.stringify({ Id: 0, Name: $("#Name").val(), StartLocation: $("#StartLocation").val(), EndLocation: $("#EndLocation").val() }), success: function (result, status, xhr) { var str = "

" + result["id"] + " " + result["name"] + " " + result["startLocation"] + " " + result[ $("table tbody").append(str); $("#resultDiv").show(); }, error: function (xhr, status, error) { console.log(xhr) } }); });

On the button click event I make an AJAX request to the API URL which is https://localhost:44324/api/Reservation.

Since the API will need Credentials for adding a reservation, therefore I have to Call the Web API with Credentials this time. The credentials are added to the HTTP Header like shown below:

headers: { Key: "Secret@123" }

Recall, the Web API Post method contains the [FromBody] attribute. So it receives the reservation parameter in the body of the api request.

In my jQuery AJAX code, I used the data parameter to send the new reservation values to the web api.

data: JSON.stringify({ Id: 0, Name: $("#Name").val(), StartLocation: $("#StartLocation").val(), EndLocation: $("#EndLocation").val() })

Once the reservation is added, the API sends back the response which contains the newly added reservation object, which is shown inside the tbody element of the table:


success: function (result, status, xhr) { var str = "

" + result["id"] + " " + result["name"] + " " + result["startLocation"] + " " + result[ $("table tbody").append(str); $("#resultDiv").show(); },

Run the page in your browser and you will be able to add a new reservation just like what is shown by the below video:

Now I will Call Web API PUT Method from jQuery. The HTTP PUT method of Web API is shown below.


[HttpPut] public Reservation Put([FromForm] Reservation res) { //… }

Start by creating a new HTML page called UpdateReservation.html. Then add the following HTML to this page:

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 & ".")

%>

How to use PHP cURL to Handle JSON API Requests
How to use PHP cURL to Handle JSON API Requests

Keywords searched by users: jquery call web api

Calling Web Api From Javascript Or Jquery [Asp.Net Core Web Api] - Youtube
Calling Web Api From Javascript Or Jquery [Asp.Net Core Web Api] - Youtube
Call Asp Net Web Api From Jquery - Youtube
Call Asp Net Web Api From Jquery - Youtube
Calling Web Api From Javascript Or Jquery [Asp.Net Core Web Api] - Youtube
Calling Web Api From Javascript Or Jquery [Asp.Net Core Web Api] - Youtube
Call (Consume) Web Api Using Jquery Ajax In Asp.Net Mvc - Youtube
Call (Consume) Web Api Using Jquery Ajax In Asp.Net Mvc - Youtube
Consuming A Web Api Asynchronously In Asp.Net Mvc Or Wpf | Dotnetcurry
Consuming A Web Api Asynchronously In Asp.Net Mvc Or Wpf | Dotnetcurry
Call Web Api Using Jquery Ajax In Asp.Net Core Web Applications
Call Web Api Using Jquery Ajax In Asp.Net Core Web Applications
Consume Asp.Net Web Api Using Jquery | Coding Knowledge | Resolve The  Errors While Consume Web Api - Youtube
Consume Asp.Net Web Api Using Jquery | Coding Knowledge | Resolve The Errors While Consume Web Api - Youtube
Sql Server, .Net And C# Video Tutorial: Call Web Api Service With Basic  Authentication Using Jquery Ajax
Sql Server, .Net And C# Video Tutorial: Call Web Api Service With Basic Authentication Using Jquery Ajax
Secure A Web Api With Individual Accounts And Local Login In Asp.Net Web Api  2.2 | Microsoft Learn
Secure A Web Api With Individual Accounts And Local Login In Asp.Net Web Api 2.2 | Microsoft Learn
Call Web Api Using Ajax | Jquery Ajax Method - Youtube
Call Web Api Using Ajax | Jquery Ajax Method - 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
Consuming Web Api From Jquery - Dot Net Tutorials
Consuming Web Api From Jquery - Dot Net Tutorials
Sql Server, .Net And C# Video Tutorial: Call Asp.Net Web Api From Jquery
Sql Server, .Net And C# Video Tutorial: Call Asp.Net Web Api From Jquery
Call Web Api Using Jquery Ajax In Asp.Net Core Web Applications
Call Web Api Using Jquery Ajax In Asp.Net Core Web Applications
Example: How To Use Jquery Ajax Method To Call An Api
Example: How To Use Jquery Ajax Method To Call An Api

See more here: kientrucannam.vn

Leave a Reply

Your email address will not be published. Required fields are marked *