Passing a global variable between functions

I have a global variable declared as var iid = ‘’;

Then I have a click event funtion that grabs the iid from within the DIV. This works.
After this I want to trigger another click event and pass the IID variable to that event but this is not working. It shows undefined in my second console log.

$(document).on('click', '.instructors_row', function(){    
    iid  = $(this).attr('id');
    console.log(iid);

    $("#i_day_events").trigger("click");

    $.ajax({
    type:"POST",
    url: "get_instructor_hours.php",
    data: {iid:iid},       
    dataType: 'html',      
    success: function(response) { 
       document.getElementById("hours_worked").innerHTML = response;
    },
    });
});  

$(document).on('click', "#i_day_events", function(event,iid) {
  event.preventDefault(); //stops form on submit  
  var period = 'DAY';
  console.log(iid); --------------------------------------- THIS SHOWS UNDEFINED
    $.ajax({
    type:"POST",
    url: "get_instructor_events_report.php",
    data: {period:period,iid:iid},       
    dataType: 'HTML',      
    success: function(response) { 
        console.log(response);
        document.getElementById('instructor_filter_box').innerHTML = response;
       },
    });
  });

Hi,

It’s not working because you’re shadowing the iid variable.

This occurs when you pass a variable of the same name into the event handler.

To remedy this, change:

to:

and all will be well.


It’s also worth pointing out that it’s not ideal to create random globals throughout your code. At the least you should declare it explicitly in your program’s upper scope. E.g.:

var iid;

$(document).on('click', '.instructors_row', function(){
  iid  = $(this).attr('id');
  console.log(iid);
  $("#i_day_events").trigger("click")
  ...
});

$(document).on('click', "#i_day_events", function(event) {
  console.log(iid);
  ...
});
1 Like

Thank you that works!

Yes I declared it in the upper scope as you mentioned

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.