Module 3: සේවාදායකයට පණිවිඩයක් යවමු

වෙබ් පිටුවෙන් ඉවත් නොවී, පසුබිමින් සේවාදායකය සමඟ සන්නිවේදනය කරන අපගේ පළමු JavaScript "පණිවිඩකරු" නිර්මාණය කරමු.

1. Test File එක සකස් කිරීම

පළමුව, අපේ project folder එකේ (live-crud-ajax), test-ajax.html නමින් අලුත් file එකක් සාදා පහත HTML කේතය ඇතුලත් කරන්න.

<!DOCTYPE html>
<html lang="si">
<head>
    <title>Ajax Test</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-5">
    <h1>Ajax Request Test</h1>
    <button id="loadDataBtn" class="btn btn-primary">Load Data from Server</button>

    <div id="responseDiv" class="mt-4 p-3 border bg-light">
        Server response will be shown here...
    </div>

    <script>
        // අපේ JavaScript කේතය මෙතනට එනවා
    </script>
</body>
</html>

2. JavaScript කේතය ලිවීම

දැන්, ඔබ සෑදූ test-ajax.html file එකේ <script> tags දෙක අතරට පහත JavaScript කේතය ඇතුලත් කරන්න.

// බොත්තම (`loadDataBtn`) click කල විට මෙම function එක ක්‍රියාත්මක වේ.
document.getElementById('loadDataBtn').addEventListener('click', function() {

    // Create a new XMLHttpRequest object
    const xhr = new XMLHttpRequest();

    // Configure the request
    xhr.open('GET', 'fetch-data.php', true);

    // Define what happens when the response is received
    xhr.onload = function() {
        if (this.status === 200) {
            document.getElementById('responseDiv').innerHTML = this.responseText;
        } else {
            document.getElementById('responseDiv').innerHTML = 'Error: ' + this.status;
        }
    };

    // Send the request
    xhr.send();
});

3. බලාපොරොත්තු විය යුතු දේ