ajax - JS global variable doesn't update

admin2025-01-07  3

How can i update global variable URL? I am trying for the last 3 days, still no luck

var output = '';
var pageNum = '';
url = '';
function post_ajax_get(pagination) {
    $("#loading-animation").show();
    var query = 'nazwa=';
    var time = 'gr=';
    var output = '';
    $("[data-category-menu] a.current").each(function(){
        if($(this).data('time')) {
            if(time != 'gr=') {
                time+= ','; 
            };
            time+= $(this).data('time');
        }
        if($(this).data('slug')) {
            if(query != 'nazwa=') {
                query+= ','; 
            };
            query+= $(this).data('slug');
        }
        if (query != 'nazwa=' && time == 'gr='){
            output = query;
        }
        else if (query == 'nazwa=' && time != 'gr='){
            output = time;
        }
        else if (query != 'nazwa=' && time != 'gr='){
            output = time + '&' + query;
        }
    });
    if(pagination) {
        $("[data-pagination] a.current").each(function(){
            if(output != '') output+= '&';
            output+= $(this).data('slug');
        });
    }
    url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + output;
    //window.location.href = url;
    if ($('body.category').length > 0 && output == '') {
        var adres = window.location.pathname;
        var cat = adres.split('/')[3];
        url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=' + cat;
        $('[data-category-menu] li a').each(function() {
            if($(this).attr('id') == cat) {
                $(this).addClass('current');
            }

            $('[data-category-menu] li a.current').click(function() {
                $(this).removeClass('current');
            }) 
        })
    }

    $('[data-category-menu] li a.current').click(function() {
        updateURL(); 
    })

    function updateURL() {
        console.log('fire');
        url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=pusty';
    }
    console.log(url);
    var pageNum = url.substr(url.indexOf("md_page=") + 8);
    //var pagNum = pageNum.toString();
    $('#md-products').load(url + ' #md-products > *', function() {
        $("#loading-animation").hide();
        $('#md-products [data-pagination] a').on('click', function() {
            $(this).addClass('current');
            post_ajax_get(true);
        })
    });
}

console.log(url);

How can i update global variable URL? I am trying for the last 3 days, still no luck

var output = '';
var pageNum = '';
url = '';
function post_ajax_get(pagination) {
    $("#loading-animation").show();
    var query = 'nazwa=';
    var time = 'gr=';
    var output = '';
    $("[data-category-menu] a.current").each(function(){
        if($(this).data('time')) {
            if(time != 'gr=') {
                time+= ','; 
            };
            time+= $(this).data('time');
        }
        if($(this).data('slug')) {
            if(query != 'nazwa=') {
                query+= ','; 
            };
            query+= $(this).data('slug');
        }
        if (query != 'nazwa=' && time == 'gr='){
            output = query;
        }
        else if (query == 'nazwa=' && time != 'gr='){
            output = time;
        }
        else if (query != 'nazwa=' && time != 'gr='){
            output = time + '&' + query;
        }
    });
    if(pagination) {
        $("[data-pagination] a.current").each(function(){
            if(output != '') output+= '&';
            output+= $(this).data('slug');
        });
    }
    url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + output;
    //window.location.href = url;
    if ($('body.category').length > 0 && output == '') {
        var adres = window.location.pathname;
        var cat = adres.split('/')[3];
        url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=' + cat;
        $('[data-category-menu] li a').each(function() {
            if($(this).attr('id') == cat) {
                $(this).addClass('current');
            }

            $('[data-category-menu] li a.current').click(function() {
                $(this).removeClass('current');
            }) 
        })
    }

    $('[data-category-menu] li a.current').click(function() {
        updateURL(); 
    })

    function updateURL() {
        console.log('fire');
        url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=pusty';
    }
    console.log(url);
    var pageNum = url.substr(url.indexOf("md_page=") + 8);
    //var pagNum = pageNum.toString();
    $('#md-products').load(url + ' #md-products > *', function() {
        $("#loading-animation").hide();
        $('#md-products [data-pagination] a').on('click', function() {
            $(this).addClass('current');
            post_ajax_get(true);
        })
    });
}

console.log(url);
Share Improve this question asked Mar 12, 2020 at 10:04 SlingySlingy 311 silver badge5 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

If you want to create global variable intentionally you need to do this.

window['your_variable_name']= 'Some variable value';

then you'll be able to access it like window.your_variable_name - this way of creating and accessing global variable guarantees that you will work with same variable regardless of what build tools like webpack or from where you access it. For example you may need to access it from other function which in turn has same named variable defined, so without referencing your variable through window.variable_name notation you'll access parent scope's variable instead of global one.

Also if you need a global variable it's name should be really unique and it's a good practice to call it like you plugin name or something that will not be overwritten by some other's code, avoid generic names like url.

So you can do this way window['YourUniquePluginGlobal'] = {url: 'your_url'};

Then you'll be able to access your variables like window.YourUniquePluginGlobal.url

Do not rely on omitting var keyword.

And even more - NEVER omit var (or let, const in ES6) when you declare a variable, as it will make your code unreliable and unmaintainable.

Always use var, let \ const when you declare a variable in JS and may the good code be with you :)

I'm not aware of whole code you use to generate markup you work with but in general after thinking based on code i see even I don't see the rest of code. I hope rewritten code might give you insight on how you can achieve what you want to be done even without global variables.

//lets init UI
$('#md-products [data-pagination] a').on('click', function () {
    $(this).addClass('current');
    var pageToLoad = $(this).attr('data-page'); // set to attribute which contains page to load.
    var url2Load = getUpdatedUrl(pageToLoad);
    post_ajax_get(url2Load);
});

$('[data-category-menu] li a').each(function () {
    var cat = getCurrentCategoryFromPathName();
    if ($(this).attr('id') === cat) {
        $(this).addClass('current');
    }
});

$('[data-category-menu] li a.current').on('click', function () {
    $(this).removeClass('current');
    updateURL();
});


/**
 * Function where you perform something - for example loading of new category's items. see above.
 */
function updateURL() {
    console.log('fire');
    // url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=pusty';
    var updatedUrl = getUpdatedUrl(0); // i guess by default you want to display first page when changing a category.
    // do something with this ulr.
    console.log(updatedUrl);
    // so really you can do to load new items.
    post_ajax_get(updatedUrl);
}


/**
 *  Really simplified just loads whetever you pass in.
 * @param  URL url_to_load
 */
function post_ajax_get(url_to_load) {

    $("#loading-animation").show();

    $('#md-products').load(url_to_load, function () {
        $("#loading-animation").hide();
    });
}


/**
 * It returns a URL bases on current category and UI states as well as receives pageNumber to load if it's paginated
 * 
 * @param pageNumber
 * @returns {string}  Url which you can load or work with.
 */
function getUpdatedUrl(pageNumber){
    var newUrl =  window.location.protocol + '//' + window.location.host + '/' + window.location.pathname;
    var query = 'nazwa=';
    var time = 'gr=';
    var output = '';

    $("[data-category-menu] a.current").each(function () {
        if ($(this).data('time')) {
            if (time != 'gr=') {
                time += ',';
            };
            time += $(this).data('time');
        }
        if ($(this).data('slug')) {
            if (query != 'nazwa=') {
                query += ',';
            };
            query += $(this).data('slug');
        }
        if (query != 'nazwa=' && time == 'gr=') {
            output = query;
        } else if (query == 'nazwa=' && time != 'gr=') {
            output = time;
        } else if (query != 'nazwa=' && time != 'gr=') {
            output = time + '&' + query;
        }
    });

    newUrl = newUrl + '?' + output;

    if ($('body.category').length > 0 && output === '') {
        var cat = getCurrentCategoryFromPathName();
        newUrl = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=' + cat;
    }

    if(pageNumber){
        newUrl = newUrl + '&md_page=' + pageNumber;
    }

    return newUrl;
}

/**
 * Just extracted logic of getting category from path.
 * @returns string
 */
function getCurrentCategoryFromPathName(){
    return  window.location.pathname.split('/')[3];
}

Again it's just blind hypotheses of code based on understanding what you wanted to achieve with your code. So it's not a copy-paste solution but i hope it will help you figure out good solution.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736252038a14.html

最新回复(0)