Sending the Request from the Client

The bulk of the work in the Web API client sample is done in a function called GetMyListings(). We're using the jQuery .ajax() function to perform an asynchronous HTTP request for the user's product listings.

The set-up parameters of $.ajax include the type of request ('GET'), the content type, and the route to the controller (see the url parameter).

Notice the composition of the url on line 5. The prefix part of the URL, /api/Listings/ is hard-coded. However, the final part is a dynamic value that comes from the username field. This corresponds to the server-side method GetUserListings(string username) where the final client-side value becomes a username parameter.

On line 7, the beforeSend attribute calls on the setHeaders() function (described previously) to generate the Authorization header.

When the server returns the requested data, the success attribute (line 8) points to the successFunc() function that receives and handles the JSON data.

If there's an error, an inline function assigns the error message text to a label using jQuery.

function GetMyListings() {
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: "/api/Listings/" + $("#txtUsername").val(),
        dataType: "json",
        beforeSend: setHeaders,
        success: successFunc,
        error: function (jqXHR, textStatus, thrownError) {
            $("#divUsername,#divPassword").show();
            $("#lblErrorMessage").show().text(thrownError
                                + " (" + textStatus + ")");
        }
    });
}

The next topic looks at how the returned list of listings is rendered in the mobile browser.

Copyright © 2002-2022. RainWorx Software. All rights reserved.