2

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!

RaggaMuffin-420
  • 1,762
  • 1
  • 10
  • 14
Grozav Alex Ioan
  • 1,559
  • 3
  • 18
  • 26

5 Answers5

7

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);
Community
  • 1
  • 1
RoToRa
  • 37,635
  • 12
  • 69
  • 105
1

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"}]
Vikram
  • 4,162
  • 8
  • 43
  • 65
1

Here is a simple example to set dynamic key and values of an array.

 var key = 1;  //your dynamic values
 var value = 2;
 var key1 = 3;
 var value1 = 5;

var myArray = new Array();
myArray[key] = value;  // set array key and values
myArray[key1] = value1;

// show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}
Rajesh Dhiman
  • 1,888
  • 1
  • 17
  • 30
0

Manage "data" as a string.

   data = "";
data += key + ":"+value;

of course a form serialize could be better if you have input in a form.

MrPk
  • 2,862
  • 2
  • 20
  • 26
0

You could try this:

JavaScript

var objects = [];

var newObject= new Object();
newObject.key = value;

objects.push(newObject);

Then, you can POST this objects-array using AJAX. In your PHP, you could retrieve the value again:

PHP:

foreach($_POST['objects'] as $object) {
    echo $object['value'];
}

Not sure if it's what you need, but it does work, if I'm correct.

Pim Verlangen
  • 387
  • 1
  • 11