4

I'm trying to send some data via ajax with jquery

var name = $(".name").attr("data-name");
var value = $(".value").attr("data-value");

$.ajax({
    url: 'panel.php',
    type: 'post',
    data: {name: value}
}).done(function(){
    alert("saved!");
});

So how can name and value be two variables. Now only value is a variable but what about name?

Cheers

2
  • Build your object before the call and set the name attribute there. Commented Jul 6, 2012 at 19:34
  • where is your on error function? I know some people like the .done() functionality, but i think it would look nicer if you have success and error in the {} Commented Jul 6, 2012 at 19:35

2 Answers 2

14

try this:

var name = "data-name";
var value = "data-value";
var dataObj = {};

dataObj[name]=value;

$.ajax({
    url: 'panel.php',
    type: 'post',
    data: dataObj,
}).done(function(){
    alert("saved!");
});​
Sign up to request clarification or add additional context in comments.

Comments

1

You need to wrap it to a DTO (Data Transfer object):

var obj = {};
obj.name = name;
obj.value = value;

//Convert to a DTO Object
var dto = { 'myData': obj };

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.