1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Push value in an empty array from a function

Discussion in 'jQuery' started by Prashant kumr, Dec 2, 2015.

  1. #2
    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):
     
    Prashant kumr, Dec 2, 2015 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    Because the category is local in scope to the function. You'll have to put the ajax code inside the function
     
    PoPSiCLe, Dec 2, 2015 IP
  3. Prashant kumr

    Prashant kumr Member

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    31
    #4
    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.
     
    Prashant kumr, Dec 2, 2015 IP