Daniel C Daniel C - 8 days ago 7
Javascript Question

Variable Scope Between JS Functions: Variable Not Defined

I am working on a script that uses jQuery get function to send information to another page and return the data as an alert on current page. I am trying to send the search field value from input form (this works), as well as the collector ID, which is a value generated by an option selected in a drop down menu above the search form.

Unfortunately, I keep getting "collector_id is undefined error" when I run the script. I think I am having an issue with the scope of the variable.. but have tried many options and can't seem to find the solution which keeps the value of collector_id for use in the get function.

$( document ).ready(function() {

$( ".search-field" ).keyup(function() {

//THIS FUNCTION UPDATES THE COLLECTOR ID VARIABLE FROM DROPDOWN MENU VALUE SELECTED BY USER
$( "select" )
.change(function () {
var collector_id = "";
$( "select option:selected" ).each(function() {
collector_id += $( this ).data('value') + " ";
});
})
.change();

//THIS FUNCTION DOES A SEARCH ON ANOTHER PHP SCRIPT PASSING search and collector_id values
if($(".search-field").val().length > 3) {
var search = $(".search-field").val();
$.get("query-include.php" , {search: search, collector_id: collector_id})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
});

});

Answer

you just need to initialize collector_id outside of the change, so it will be in scope for the $.get

var collector_id = "";
$( "select" )
.change(function () {
    $( "select option:selected" ).each(function() {
        collector_id += $( this ).data('value') + " ";
    });
})
.change();

//THIS FUNCTION DOES A SEARCH ON ANOTHER PHP SCRIPT PASSING search and collector_id values
if($(".search-field").val().length > 3) {
    var search = $(".search-field").val(); 
    $.get("query-include.php" , {search: search, collector_id: collector_id})
    .done(function( data ) {
        alert( "Data Loaded: " + data );
    });
}
}); 
Comments