jeudi 3 décembre 2015

change ajax jquery url from checkbox selection

I have four checkbox and I am retrieving some JSON data from an API using Jquery AJAX and I want to change the URL dynamically on checkbox selection. When I put ajax code inside click function its working but from outside click function its not working. In fact I can't access category array outside the click function. I want to store the value of category to a global variable or array, So I can access it in ajax code or somewhere else in my code and I can't figure out how to do that.

var category = [];
$(".ckbox").click(function() {
  if ($(this).is(":checked")) {
    category.push($(this).val());
  } else {
    var x = category.indexOf($(this).val());
    category.splice(x, 1);
  }
  console.log(category); //show array on checkbox clicking
});
console.log(category); //show empty array

$.ajax({
  url: 'http://ift.tt/1OHWDX5?',
  dataType: 'json',
  type: 'GET',
  data: {
    category: category,
    city: 'PUNE',
    begin: '0',
    limit: '200',
  },
  traditional: true,
  success: function(response) {
    console.log(response);
  },
  error: function(err) {
    alert("something went wrong.");
    console.log(err);
  }
});



Aucun commentaire:

Enregistrer un commentaire