ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalEC-332Rest Consumption
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    EC-332

    Enterprise Application Development

    Progress0 / 37 done
    Topics37
    1Microsoft technology history2Introduction to .NET and its architecture3Concept of MSIL, CLR, CLS, CTS
    4Managed and Unmanaged Code5.Net Assembly6Introduction to C# fundamentals7Boxing and Unboxing8Implementing multi-tier architecture
    9SQL Injection, parameterized queries10Usage of data set, Data adapter and command builder in disconnected model
    11Multicast delegates12Introduction to windows forms13HTML
    14javascript and its data types, variables, functions15Debugging javascript using Firebug
    16Browser's Object (BOM), Document Object Model
    17Jquery effects
    18LINQ to Objects, LINQ to SQL19Query syntax, Operations (projection, filtering and join) using Linq Queries
    20The entity data model, CSDL21Eager vs lazy loading, POCO classes, DBContext API22Querying entity data models23Introduction to ASP.NET MVC24MVC application structure, Controllers overview25Action Methods, Parameterized action methods26Introduction to razor syntax27Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28Data annotations, Client and Server Side Validation29Validation and model binding, Validation and model state30MVC Membership, Authorization and security
    31SOAP, WSDL32Service contract, Data contract, XML, WCF bindings33ABC of WCF, Restful services34Consuming rest services (CRUD operations) using Jquery AJAX and JSON35Introduction to web API36Example of web API using CRUD Example37MVC routing
    8 min read
    Topic 34 of 37
    Topic Study Note Illustration
    34

    Consuming rest services (CRUD operations) using Jquery AJAX and JSON

    When consuming RESTful services from a web client, jQuery and AJAX (Asynchronous JavaScript and XML) are commonly used to make HTTP requests and interact with RESTful APIs....

    Consuming REST Services (CRUD operations) using jQuery AJAX and JSON

    When consuming RESTful services from a web client, jQuery and AJAX (Asynchronous JavaScript and XML) are commonly used to make HTTP requests and interact with RESTful APIs. The most common format for transferring data between the client and the server in REST APIs is JSON (JavaScript Object Notation).

    In this guide, we'll cover how to perform CRUD (Create, Read, Update, Delete) operations using jQuery AJAX and JSON for consuming RESTful services.

    Overview of CRUD Operations:

    • Create (POST): Sends data to the server to create a new resource.
    • Read (GET): Retrieves data from the server (e.g., a list of resources or a single resource).
    • Update (PUT or PATCH): Sends updated data to the server to modify an existing resource.
    • Delete (DELETE): Sends a request to remove a resource from the server.

    Step-by-Step Guide to CRUD Operations with jQuery AJAX

    Assuming the API you're consuming has endpoints like the following:

    • GET /api/books: Get a list of all books.
    • GET /api/books/{id}: Get a specific book by its id.
    • POST /api/books: Add a new book.
    • PUT /api/books/{id}: Update an existing book.
    • DELETE /api/books/{id}: Delete a book.

    Let’s look at how to consume these operations using jQuery AJAX and JSON.


    1. Create (POST): Adding a New Book

    To add a new book, you would send a POST request with the book data (in JSON format) to the RESTful service.

    Example jQuery AJAX for Creating a Book:

    $(document).ready(function () {
        $('#addBookBtn').click(function () {
            var bookData = {
                title: $('#title').val(),
                author: $('#author').val(),
                year: $('#year').val()
            };
    
            $.ajax({
                url: 'http://localhost:8080/api/books',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(bookData),
                success: function (response) {
                    alert('Book added successfully!');
                    // Optionally reload the list of books after adding
                    loadBooks();
                },
                error: function (xhr, status, error) {
                    alert('Error: ' + error);
                }
            });
        });
    });
    
    • Explanation:
      • The bookData object contains the details of the book that you want to add.
      • The $.ajax() method sends a POST request to the API endpoint.
      • The contentType is set to application/json because we're sending JSON data.
      • The data is the JSON stringified version of bookData.
      • On success, we alert the user and reload the list of books by calling loadBooks(), which you will implement in the "Read" operation.

    2. Read (GET): Retrieving All Books

    To get all books, you would send a GET request to the /api/books endpoint.

    Example jQuery AJAX for Retrieving Books:

    function loadBooks() {
        $.ajax({
            url: 'http://localhost:8080/api/books',
            type: 'GET',
            dataType: 'json',
            success: function (response) {
                var booksList = $('#booksList');
                booksList.empty(); // Clear the current list of books
                response.forEach(function (book) {
                    booksList.append('<li>' + book.title + ' by ' + book.author + '</li>');
                });
            },
            error: function (xhr, status, error) {
                alert('Error: ' + error);
            }
        });
    }
    
    $(document).ready(function () {
        loadBooks(); // Load books on page load
    });
    
    • Explanation:
      • The loadBooks() function sends a GET request to the /api/books endpoint.
      • The server's response is expected to be in JSON format (dataType: 'json').
      • We loop through the list of books (response) and display them in an unordered list (#booksList).

    3. Update (PUT): Updating an Existing Book

    To update an existing book, you would send a PUT request with the updated book data to the /api/books/{id} endpoint.

    Example jQuery AJAX for Updating a Book:

    $(document).ready(function () {
        $('#updateBookBtn').click(function () {
            var bookId = $('#bookId').val(); // ID of the book to update
            var bookData = {
                title: $('#title').val(),
                author: $('#author').val(),
                year: $('#year').val()
            };
    
            $.ajax({
                url: 'http://localhost:8080/api/books/' + bookId,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(bookData),
                success: function (response) {
                    alert('Book updated successfully!');
                    loadBooks(); // Reload the list of books
                },
                error: function (xhr, status, error) {
                    alert('Error: ' + error);
                }
            });
        });
    });
    
    • Explanation:
      • The bookId is the ID of the book to be updated, taken from the input field #bookId.
      • The bookData object contains the updated data for the book.
      • The PUT request sends the updated bookData as JSON to the /api/books/{id} endpoint.
      • After a successful update, we reload the list of books.

    4. Delete (DELETE): Deleting a Book

    To delete a book, you would send a DELETE request to the /api/books/{id} endpoint, where id is the ID of the book to be deleted.

    Example jQuery AJAX for Deleting a Book:

    $(document).ready(function () {
        $('#deleteBookBtn').click(function () {
            var bookId = $('#bookId').val(); // ID of the book to delete
    
            $.ajax({
                url: 'http://localhost:8080/api/books/' + bookId,
                type: 'DELETE',
                success: function (response) {
                    alert('Book deleted successfully!');
                    loadBooks(); // Reload the list of books
                },
                error: function (xhr, status, error) {
                    alert('Error: ' + error);
                }
            });
        });
    });
    
    • Explanation:
      • The bookId is the ID of the book to be deleted, taken from the input field #bookId.
      • The DELETE request sends a request to the /api/books/{id} endpoint.
      • On success, the book is removed, and we reload the list of books.

    Summary:

    • Create (POST): Use AJAX to send JSON data to the server to create a new resource.
    • Read (GET): Use AJAX to retrieve data from the server and display it on the page.
    • Update (PUT): Use AJAX to send updated data to the server to modify an existing resource.
    • Delete (DELETE): Use AJAX to delete a resource from the server.

    Example HTML (to interact with the AJAX operations):

    <!DOCTYPE html>
    <html>
    <head>
        <title>Books CRUD Operations</title>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="script.js"></script> <!-- Include your script file -->
    </head>
    <body>
    
    <h1>Books CRUD Operations</h1>
    
    <!-- Create Book Form -->
    <input type="text" id="title" placeholder="Book Title">
    <input type="text" id="author" placeholder="Author">
    <input type="number" id="year" placeholder="Year">
    <button id="addBookBtn">Add Book</button>
    
    <br><br>
    
    <!-- Update Book Form -->
    <input type="number" id="bookId" placeholder="Book ID to update">
    <button id="updateBookBtn">Update Book</button>
    
    <br><br>
    
    <!-- Delete Book Form -->
    <input type="number" id="bookId" placeholder="Book ID to delete">
    <button id="deleteBookBtn">Delete Book</button>
    
    <h2>Books List</h2>
    <ul id="booksList"></ul>
    
    </body>
    </html>
    

    With this setup, your HTML form allows you to create, read, update, and delete books using the corresponding AJAX operations. Each operation interacts with the REST API using JSON and jQuery.

    ← Previous topic 33
    ABC of WCF, Restful services
    Next topic 35 →
    Introduction to web API

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.3kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Enterprise Application Development