cferdinandi / atomic

A tiny, Promise-based vanilla JS Ajax/HTTP plugin with great browser support.
MIT License
540 stars 78 forks source link

Converting from jquery #88

Closed oldcastlehq closed 4 years ago

oldcastlehq commented 4 years ago

I'm quite new to JS, so I've being using jquery, but I would like to move to vanilla. I have this Ajax in jquery:

$('#category').change(function() {
    var categoryID = $(this).val();
    var dataURL = $(this).data('url') + 'taxonomy/get_sub/'+categoryID;

    $.ajax({
        url: dataURL,
        method: 'POST',
        success:function(data) {
            $('#sub_category').html(data);
        }
    });
});

Can I do the same thing with atomic?

juliendude commented 4 years ago

Hi @oldcastlehq Welcome to the javascript. Everything that you can do with jQuery can be done in plain javascript. Atomic is a plugin to simplify your life when getting or posting data using ajax. You write less code to achieve your result. Therefore it will only handle the "$.ajax({...});"part of your code. You also need to make the change function.

I highly recommend reading more on Chris's website. It's a gold mine. And the best way is to get hands dirty and try it for yourself. jQuery is actually very similar to plain javascript.

cferdinandi commented 4 years ago

Great response, @julienbenisty! (FWIW, I actually am all-in on Fetch now)

@oldcastlehq you can, and you can actually do it with Atomic either using the fetch method.

// Get the #category element
var category = document.querySelector('#category');
var subCategory = document.querySelector('#sub_category');

// Listen for changes to the #category element
category.addEventListener('change', function (event) {

    // Get the category ID and URL
    var dataURL = event.target.getAttribute('data-url') + 'taxonomy/get_sub/' + event.target.value;

    fetch(dataURL).then(function (response) {
        return response.json();
    }).then(function (data) {
        subCategory.innerHTML = data;
    });

});