ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Enterprise Application Development
    EC-332
    Progress0 / 37 topics
    Topics
    1. Overview of Enterprise Application Development: Microsoft technology history2. Introduction to .NET and its architecture3. Concept of MSIL, CLR, CLS, CTS4. Introduction to .NET framework: Managed and Unmanaged Code5. .Net Assembly6. Introduction to C# fundamentals7. Boxing and Unboxing8. Implementing multi-tier architecture9. Introduction to ADO.Net: SQL Injection, parameterized queries10. Usage of data set, Data adapter and command builder in disconnected model11. Introduction to delegate: Multicast delegates12. Introduction to windows forms13. HTML14. Introduction to javascript: javascript and its data types, variables, functions15. Debugging javascript using Firebug16. Introduction to various object models: Browser's Object (BOM), Document Object Model17. Introduction to Jquery: Jquery effects18. Introducing LINQ: LINQ to Objects, LINQ to SQL19. Query syntax, Operations (projection, filtering and join) using Linq Queries20. Introduction to ADO.NET entity framework: The entity data model, CSDL21. Eager vs lazy loading, POCO classes, DBContext API22. Querying entity data models23. Introduction to ASP.NET MVC24. MVC application structure, Controllers overview25. Action Methods, Parameterized action methods26. Introduction to razor syntax27. Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28. Data annotations, Client and Server Side Validation29. Validation and model binding, Validation and model state30. MVC Membership, Authorization and security31. Introduction to service-oriented architecture: SOAP, WSDL32. Service contract, Data contract, XML, WCF bindings33. ABC of WCF, Restful services34. Consuming rest services (CRUD operations) using Jquery AJAX and JSON35. Introduction to web API36. Example of web API using CRUD Example37. MVC routing
    EC-332›Consuming rest services (CRUD operations) using Jquery AJAX and JSON
    Enterprise Application DevelopmentTopic 34 of 37

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

    8 minread
    1,302words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,302
      Code examples0
      DifficultyIntermediate