Jason Wells
Jason Wells

Reputation: 889

Building the data portion of $.ajax dynamically

I have a need to build the data string dynamically. This is not working, as it is just passing the param variable as a string.

var parameters = "{foo: 'test'}";
    $.ajax({
        url: 'test.php',
        data: parameters,
        type: 'get',
        dataType: 'json
    });

Any ideas?

Upvotes: 0

Views: 98

Answers (2)

tobyodavies
tobyodavies

Reputation: 28099

var parameters = {foo:'test'};
//modify `parameters` dynamicaly
parameters[bar]='dynamic!';
$.ajax({
    //...
    data: (sendJSON?JSON.stringify(parameters):parameters) // sends params either JSON or form encoded
    //...
});

Upvotes: 0

raina77ow
raina77ow

Reputation: 106375

Well, first you assign a string to parameters variable, but then expect it to turn into object? ) Use object in the first place, like this:

var params = {foo: 'test'};
$.ajax({..., data: params, ...});

Upvotes: 1

Related Questions