I am retrieving some JSON data from an API using Jquery AJAX and I want to change the URL dynamically on checkbox selection. I have four checkbox and I want to store checkbox value to an globle array. When I put console.log(category) or ajax code inside function its working but when I put the code outside the function its not working. var category = []; $(".ckbox").click(function() { if($(this).is(":checked")) { category.push($(this).val()); } else { var x = category.indexOf($(this).val()); category.splice(x, 1); } }); $.ajax({ url: 'https://godrejapi-dot-indiacomapi.appspot.com/_ah/api/godrej/v1/godrejestablishment?', dataType: 'json', type: 'GET', data: { category: category, //I wnat to change this city: 'PUNE', begin: '0', limit: '200', }, traditional: true, success: function(response){ // console.log(response); }, error: function(err){ alert("something went wrong."); console.log(err); } }); Code (JavaScript):
Because the category is local in scope to the function. You'll have to put the ajax code inside the function
When I put ajax code inside the function, it's working but I want ajax code outside. I want to store the value of category to a global variable, So I can access it in ajax code and I can't figure out how to do that.