jQuery AJAX

লেসন ৪১ / ৪৪

jQuery AJAX

jQuery AJAX-কে অত্যন্ত সহজ করেছিল। আজও অনেক legacy প্রজেক্টে ব্যবহৃত।

$.ajax() — সম্পূর্ণ control

$.ajax({
    url: "https://api.example.com/users",
    method: "GET",
    dataType: "json",
    data: { page: 1, limit: 10 },
    headers: {
        "Authorization": "Bearer TOKEN"
    },
    timeout: 5000,

    beforeSend: function() {
        $("#loader").show();
    },
    success: function(data) {
        console.log("সফল:", data);
        renderUsers(data);
    },
    error: function(xhr, status, error) {
        console.error("ভুল:", error);
    },
    complete: function() {
        $("#loader").hide();
    }
});

$.get() — সহজ GET

$.get("/api/users", function(data) {
    console.log(data);
});

// Query parameter সহ
$.get("/api/search", { q: "web", page: 1 }, function(data) {
    console.log(data);
});

$.post() — সহজ POST

$.post("/api/users",
    { name: "করিম", age: 25 },
    function(response) {
        console.log("তৈরি হয়েছে:", response);
    }
);

$.getJSON() — JSON data

$.getJSON("/api/users", function(users) {
    $.each(users, function(i, user) {
        $("#list").append(`<li>${user.name}</li>`);
    });
});

Promise-style (Deferred)

$.ajax({
    url: "/api/users",
    method: "GET"
})
.done(function(data) {
    console.log("সফল:", data);
})
.fail(function(xhr, status, error) {
    console.error("ভুল:", error);
})
.always(function() {
    $("#loader").hide();
});

Form Submit with AJAX

$("#myForm").on("submit", function(e) {
    e.preventDefault();   // default submit বন্ধ

    $.ajax({
        url: $(this).attr("action"),
        method: "POST",
        data: $(this).serialize(),   // form data → query string
        success: function(res) {
            $("#message").text("সফল!");
            $("#myForm")[0].reset();
        },
        error: function() {
            $("#message").text("ভুল হয়েছে!");
        }
    });
});

// File Upload সহ
$("#uploadForm").on("submit", function(e) {
    e.preventDefault();
    $.ajax({
        url: "/upload",
        method: "POST",
        data: new FormData(this),
        contentType: false,
        processData: false,
        success: function(res) { console.log(res); }
    });
});

$.ajaxSetup() — সব request এর ডিফল্ট

$.ajaxSetup({
    headers: {
        "Authorization": "Bearer " + localStorage.getItem("token"),
        "X-CSRF-Token": csrfToken
    }
});
// এখন প্রতিটি $.ajax-এ এই header যাবে

jQuery AJAX vs fetch — তুলনা

// jQuery
$.get("/api/users", function(data) {
    console.log(data);
});

// Fetch (আধুনিক)
fetch("/api/users")
    .then(r => r.json())
    .then(data => console.log(data));