0

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 );
    });
  }
   }); 

  });
2
  • Please fix your intendation. It's nearly impossible to reason about code that is not properly indented. Commented Nov 26, 2016 at 19:36
  • 2
    collector_id is a variable scoped to the change handler. There's no collector_id defined anywhere else. Commented Nov 26, 2016 at 19:38

1 Answer 1

1

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 );
    });
}
}); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.