#how to clean up my ajax code?

4 messages · Page 1 of 1 (latest)

acoustic sail
#

hey guys. can smb help me out? im trying to clean up the code so its more readable.i started with this:

function autocompleteCity() {
    $( ".city-autocomplete" ).on( "input", function() {
        $.ajax({
            method: "POST",
            url: '?m=customeradd',
            data: {
                search : $(this).val(),
                state:   $('.state-options').find(":selected").data('id-sav'),
                mode : 'city'
            },
            success: function(data){
                $('#city-autocomplate-wrapper').empty();
                let result = JSON.parse( data );

                let autoElem = '<div class="auto-elem">';
                $.each( result, function( key, value ) {
                    let select = '<div class="autocompleter-elem"><span data-id="'+ value.id_reg_centras +'">' + value.name  +' '+ value.short_type +'</span> </div>'
                    autoElem = autoElem.concat(" ", select);
                });
                autoElem = autoElem.concat(" ", '</div>');
                $( "#city-autocomplate-wrapper" ).append( autoElem );
            }
        });
    } );
}

and so far i have this:

function getCitiesForAutocomplete(searchValue, stateId) {
    const ajaxRequest = {
        method: 'POST',
        url: '?m=customeradd',
        data: {
            search: searchValue,
            state: stateId,
            mode: 'city'
        }
    };

what to do next? id like to work on making that success function (or whatever it is) more readable. can smb help me out or give some guidance? much appreciated 😄

static saddle
#

well... drop jQuery and use fetch would be my first instinct, tbh, as it makes use of async and thereby makes your code flatter.

MDN Web Docs

The Fetch API provides a JavaScript interface for making HTTP requests and processing the responses.

acoustic sail
static saddle
#

Where do you face blockers exactly?