1

I'm trying to do this:

$.ajax({
   type: "PUT",
   url: /example,
   data: {_method: "put", "foo_model[bar_attribute]": value_var }
});

And works as expected but I need to construct the part foo_model[bar_attribute]dynamically.

I'm trying with:

var model = "foo_model";
var attribute = "foo_attribute";
var param = model + "[" + attribute + "]";
var dataStr = '{_method: "put",' + param + ': ' + value + '}';

and again:

$.ajax({
   type: "PUT",
   url: /example,
   data: dataStr
});

But it doesn't work, jQuery is escaping quotes and adding curly brackets everywhere around...

Is there any better way to do this? I also tried other ways like making a json object, setting processData to false, as I saw in another post but nothing seems to be working... The request is always transformed and escaped. Also tried unescape but it only works if I write literally:

data: {_method: "put", "foo_model[bar_attribute]": value_var }

Thanks.

1 Answer 1

1

You can just use something like this (tested and working)

var model = "foo_model";
var attribute = "foo_attribute";
var param = model + "[" + attribute + "]";
var value = "test";

$.ajax({
  url: "http://fiddle.jshell.net/pu6ME/show/",
  type: "GET",
  data: param + '=' + value
}).done(function() {
   alert("Works!");
});

By using the param + '=' + value workaround you can actually use a dynamic name! I believe it is not possible by using normal key : value syntax, but it doesn't matter in this example.

No need to define datastring.

JSFiddle example (use Control/Cmd + I to view network activity, and you'll see it works)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.