Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  150] [ 1]  / answers: 1 / hits: 28155  / 10 Years ago, wed, march 12, 2014, 12:00:00

I want to send key value pairs to my php page, but I need to set the key and value dynamically from data tags.



Here's the code I have until now:



function send(){
var attr = new Array();

var key = $('#add').attr('data-key');
var value = $('#add').attr('data-value');

attr.push({ key : value });

var data = {attributes: attr};

$.ajax({
url: ajax.php,
type: POST,
data: data,
success: function(result) {
alert(result)
}
});

}


This is not the actual code, it's just the basic functionality.



The problem is here:



attr.push({ key : value });


The 'key' is not taken as the variable I've set.



Can I please get some help? I'd really appreciate it. Thank you very much!


More From » jquery

 Answers
3

Update:


Since ECMAScript 6 (2015) it's possible to use computed object property names, which is supported by all current browsers and other JavaScript environments:


attr.push({ [key] : value });




Original Answer:


Use the bracket notation:


Instead of attr.push({ key : value }); use


var object = {}; 
object[key] = value;
attr.push(object);

[#72031] Tuesday, March 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jimmieo

Total Points: 515
Total Questions: 102
Total Answers: 110

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;