Search code examples
jquerybackbone.jsunderscore.js

Dynamicly adding paramteters to an ajax call based on a variables state


I have an ajax call that has a list of parameters that it needs to pass to its data object. But this list changes based on a certain category. So I'm trying to find a way to filter through the ones I need and the ones I don't need.

$.ajax({
    url:'......',
    type:'post',
    dataType:'json',
    data: {
        'api': 'myApilist',
        'address' : 'someaddress',
        'callTime' : _this.get('calltime'),
        'id1' : _this.get('id1'),
        'id2' : _this.get('id2'),
        'type' : _this.get('type'),
        'options': _this.get("options"),
        'mode' : _this.get('mode'),
        'time' : _this.get('time')
        'method' : 'POST'
    },

Sometimes id1 and id2 are not needed based on a state I have setup. So if the state="time" then the id1 and id2 don not need to be part of the data list. And if the state="id" then both ids need to be in there.

I was trying to use the filter loops in _underscore to try and filter out these options based on my state but it didn't work as I don't understand them correctly. How would I go about this.

_this.get("options") is referring to a Backbone model.


Solution

  • You have to build your data string before you pass it in the ajax call. This is one way you can do:

    var dynData = new Object();
    dynData.api = <value>;
    dynData.address = <value>;
    

    Looks static as of now. Now based on your 'state', you can add properties to the javascript object on the fly using the following:

    dynData["newProperty"] = <value>;
    

    Now using JSON and json2.js, you can create your JSON string using:

    data:JSON.stringify(dynData);     
    

    Mark as answer if this worked :)