corroded
corroded

Reputation: 21564

how do you make ajax data key dynamic in jquery?

I'm trying to make my inline edit to be dynamic so it will just depend on some data- attributes from my markup so here's the code for now:

$(".inline-edit").editable(
  function(value, settings) {
    var editableField = $(this);

    $.ajax({
          type: 'PUT',
          url: editableField.attr('data-href'),
          dataType: 'html',
          success: function(html) {
            editableField.parents('.replaceable').replaceWith(html);
          },
          data: { 'regression_test_environment[name]' : value }
        });
        return(value);
  },
  {
    event: 'click',
    width: '80%',
    height: '20',
    submit : 'OK'
  }
)

i want the name in regression_test_environment[name] to be editableField.attr('data-column-name') but it always fails in compiling because it keeps taking the key as a string. I tried making a variable after the editable field variable assignment and building the string as a different variable but it doesn't want to evaluate the key as a function.

Is there a way to do this? or am i stuck in creating a separate .editable call for each of my editable fields?

Upvotes: 13

Views: 23374

Answers (3)

DShah
DShah

Reputation: 472

Best is to pass dynamic values by serializing it :

    var data = $('#formid').serialize(); // serialize all the data in the form 
    $.ajax({
    url: 'test.php', // php script to retern json encoded string
    data: data,  // serialized data to send on server
    ...
    });

Upvotes: 0

keithhackbarth
keithhackbarth

Reputation: 10146

Better, less confusing answer:

var data = {};
data[thisField] = $(this).text();

$.ajax({
    data: data
});

Upvotes: 20

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

You may try like this:

var name = editableField.data('column-name');
var values = { };
values['regression_test_environment[' + name + ']'] = value;

$.ajax({
    type: 'PUT',
    url: editableField.data('href'),
    dataType: 'html',
    data: values,
    success: function(html) {
        editableField.parents('.replaceable').replaceWith(html);
    }
});

Upvotes: 21

Related Questions