E
E
Egor Mikheev2015-11-02 21:35:49
JavaScript
Egor Mikheev, 2015-11-02 21:35:49

How to return a variable from a function that overrides the previous value of the variable?

Hello, not the first time I encounter a problem, the solution of which was postponed until later. Actually for not beginners anything difficult.

var set = "https://авава.me/c_parser.php?type=getjson&set=mMoscow";

  $(document).ready(function() {       
           $('#drop-list').on("select2:open", function (set) { 
             var table = $('.json.active').attr('id'); //идентификатор таблицы
             var city = $('#city').val(); //идентификатор города
             var set = "../../../../c_respond.php?type=getTable&city="+city+"&nameTable="+table;
             console.log(set); 
            });
  
            $('#drop-list').select2({
                minimumInputLength: 2,
        ajax: {
            url: set,
            dataType: 'json',
            data: function (term,page) {
                return {
                    q: term              
                  };
.........


there are 3 parts:
1) Declaring the set variable when the system boots,
2) Redefining the set variable when events occur.
3) Substitution of the set variable in the request.
Here something is not glued, for some reason the variable is not redefined.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yaroslav Lyzlov, 2015-11-02
@ogregor

You should not write window.set, and for what, never. Then everything in the world will hurt from this, when in one file you have window.blabla = 1, in another window.blabla = 5 and you will run around looking for what is wrong. It's just worth dealing with the scope:
https://learn.javascript.ru/functions-closures

A
Adamos, 2015-11-02
@Adamos

var set inside a function is the definition of a local variable, which has nothing to do with the global one. Reference to set later in the function refers to a local variable, reference elsewhere to a global variable.
Until you get comfortable with scopes, write global variables as window.set - this is the same thing, but it will be much more difficult to make a mistake.

Y
Yuri, 2015-11-02
@kapitan7830

remove var like this and it will work,
but in general, as already advised above,
understand scopes
so that such problems
do not arise

$('#drop-list').on("select2:open", function () { 
             var table = $('.json.active').attr('id'); //идентификатор таблицы
             var city = $('#city').val(); //идентификатор города
             set = "../../../../c_respond.php?type=getTable&city="+city+"&nameTable="+table;
             console.log(set); 
            });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question