0

Here I want to do which are the variable not empty, I want to pass that variable one in data,in this case area is empty so I want pass the parameter for city and listing type, but I don't know how to do?

var city = "Karnadaka";
var area = "";
var listing type = "RENT";

$.ajax({
    type: 'GET',
    url: "http://www.domain.com/api/get/searchProperties",
    data: {
        area: area,
        city: city,
        listingType: listing_type
    },
    success: function(data) {
        console.log(data);
    }
});
  • 3
    Create an object, check if value is not empty then add to object `var data = {}; if (area) { data.area = area; } if (city) { data.city = city; } ...` And use this object to pass `data` to ajax request `data: data,` – Tushar Dec 26 '16 at 06:41
  • From where i have to check this empty or not, can pls update your answer – Sagunthala K Dec 26 '16 at 06:51

2 Answers2

1

you can use delete to remove the propery pair(s) in an Object

var city = "Karnadaka";
var area = "";
var listing_type = "RENT";

var data={
        area: area,
        city: city,
        listingType: listing_type
    }

for (k in data){
    if(data[k]=="") delete data[k];
}

$.ajax({
    type: 'GET',
    url: "http://www.domain.com/api/get/searchProperties",
    data: data,
    success: function(data) {
        console.log(data);
    }
});
Liang
  • 507
  • 2
  • 9
0

Try this:

var city = "Karnadaka";
var area = "";
var listing_type = "RENT";

var data = {};

if(city != '')
    data['city'] = city;

if(area != '')
    data['area'] = area;

if(listing_type != '')
    data['listing_type'] = listing_type;

$.ajax({
    type: 'GET',
    url: "http://www.domain.com/api/get/searchProperties",
    data: data,
    success: function(response) {
        console.log(response);
    }
});
Yajnesh Rai
  • 290
  • 1
  • 6
  • 17
  • Yajnesh Rai @ your code is woking but while going dynamic it is not working that means area is ,i tried console.log(area) it is coming blank so that time it is not working what i have to do – Sagunthala K Dec 26 '16 at 07:22
  • Thanks @SagunthalaK. If there is any further requirement on dynamic code, please post that as well – Yajnesh Rai Dec 27 '16 at 06:33