Jordan Richards
Jordan Richards

Reputation: 542

How can I input a dynamic data argument for the jQuery post?

I'm trying to make this work.

function postCharacter(id, type) {
  type = type;
  id = id;
  var data = type + ':' + id; 
  $.post('', {data});
}

Hopefully from that example you can see what I'm trying to achieve. But if not, what I'm trying to do.

$.post('', {a, b}); 

both a and b are values that are dynamic, How can I input a dynamic data argument for the jQuery post? What I tried unfortunately did not work.

Upvotes: 1

Views: 1052

Answers (3)

jmif
jmif

Reputation: 1212

Instead of

var data = type + ':' + id;
$.post('', {data});

do this

var data = { type: id };
$.post('', data);

If you pass a JavaScript object jQuery will go through and put those in the request for you. In this way you can add as many dynamic values to the request without having to generate the string. If you want to add a second parameter it would look like this (where id and id2 are variables):

var data = { type: id, type1: id2 }

Also, you don't need to have these two lines:

type = type
id = id

as they're already set in the function arguments.

Upvotes: 0

nicosantangelo
nicosantangelo

Reputation: 13726

data is an object so, you could so something like:

function postCharacter(id, type) {
  var data = {};
  dara[type] = id; 
  $.post('', data);
}

Upvotes: 0

Pointy
Pointy

Reputation: 413737

You need to create the object first and then add the properties:

var data = {};
data[type] = id;

You don't need the first two lines of your function at all; they don't do anything.

Then the $.post call should be:

$.post(url, data);

Upvotes: 1

Related Questions