ConfusedLuigi ConfusedLuigi - 5 months ago 8
Ajax Question

Using a local variable out of an event handler function that makes an ajax call in Javascript

What would be the best way to get the value of the variable "search" from the first function to use it on the last ajax call? I know I could use closure but not sure how. Here's my code:

$(document).on("click", ".box", function(){
var search = $(this).attr("alt");
$.ajax({
method: "GET",
url: url + search,
success: function(data){
console.log(data);
}
})
});

$( ".select" ).change(function(){
var param2 = $(this).val();
$.ajax({
method: "GET",
url: url + search + param2,
success: function(data){
console.log(data);
}
})
});

Answer

Using a closure is as simple as declaring the variable outside the scope of both functions:

var search;

$(document).on("click", ".box", function(){
  search = $(this).attr("alt");
  $.ajax({
    method: "GET",
    url: url + search,
    success: function(data){
      console.log(data);
    }
  })
});

$( ".select" ).change(function(){
 var param2 = $(this).val();
 $.ajax({
    method: "GET",
    url: url + search + param2,
    success: function(data){
      console.log(data);
    }
  })
});