Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery array set both key and value and send array via AJAX

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!

like image 439
Grozav Alex Ioan Avatar asked Dec 29 '25 10:12

Grozav Alex Ioan


2 Answers

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);
like image 196
RoToRa Avatar answered Dec 30 '25 22:12

RoToRa


If you did this:

var key = "abc", value="pqr";
arr.push({key: value});

It would have following:

[Object { key="pqr"}]

which is not what you wanted..

You have to be able to do this:

var arr = new Array();
keyValuePair = {};
keyValuePair[key]=value; // set your dynamic values

arr.push(keyValuePair);

Now you have:

[Object { abc="pqr"}]
like image 20
Vikram Avatar answered Dec 30 '25 23:12

Vikram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!