Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Simplifying AJAX Requests with jQuery.ajax()

Tech 2

AJAX requests typically involve repetitive code patterns, and handling responses with vanilla JavaScript can be cumbersome. jQuery streamlines this process by providing built-in support for asynchronous HTTP rqeuests and response handling, significantly reducing the copmlexity of implementing AJAX functionality.

Basic Usage of jQuery.ajax()

The standard syntax for making an AJAX request using jQuery is as follows:

Frontend Code

<html>
<head>
    <meta charset="UTF-8">
    <title>Dynamic Username Validation</title>
    <script src="js/jquery.min.js"></script>
    <script>
        function validateUsername() {
            const inputField = $('#usernameInput');
            const feedbackElement = $('#validationMessage');

            if (!inputField.val() || inputField.val().trim() === '') {
                feedbackElement.text('Username is required.');
                return;
            }

            feedbackElement.text('');

            $.ajax({
                type: 'GET',
                url: 'validateUsername.do',
                data: { username: inputField.val() },
                success: function(response) {
                    feedbackElement.text(response);
                }
            });
        }
    </script>
</head>
<body>
    <form action="submitForm.do">
        Username: <input id="usernameInput" type="text" name="username" onblur="validateUsername()">
        <span id="validationMessage" style="color: red;"></span><br>
        Password: <input type="password" name="password"><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Backend Code

package com.msb.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/validateUsername.do")
public class UsernameValidatorServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String message = "";

        if ("admin".equals(username)) {
            message = "This username is already taken.";
        } else {
            message = "Username is available.";
        }

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().print(message);
    }
}

Handling JSON Responses

When working with JSON data, jQuery automatically parses the response if the dataType option is set to json.

Frontend Code

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Fetch JSON Data via AJAX</title>
    <script src="js/jquery.min.js"></script>
    <script>
        function fetchStudentData() {
            $.ajax({
                type: 'GET',
                url: 'studentList.do',
                data: { user: 'zhangsan', pass: '123456' },
                dataType: 'json',
                success: function(data) {
                    $.each(data, function(index, student) {
                        console.log(student.name + ', ' + student.gender + ', ' + student.age);
                    });
                }
            });
        }
    </script>
</head>
<body>
    <button onclick="fetchStudentData()">Load Data</button>
</body>
</html>

Backend Code

package com.msb.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.msb.model.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

@WebServlet("/studentList.do")
public class StudentListServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("user");
        String password = req.getParameter("pass");
        System.out.println("User: " + username);
        System.out.println("Pass: " + password);

        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("Zhang", "Male", 20, new Date()));
        students.add(new Student("Li", "Female", 19, new Date()));
        students.add(new Student("Wang", "Male", 21, new Date()));
        students.add(new Student("Chen", "Female", 18, new Date()));

        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat("yyyy-MM-dd");
        Gson gson = builder.create();
        String jsonOutput = gson.toJson(students);

        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().print(jsonOutput);
    }
}
Tags: jQuery

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.