views:

31

answers:

2

I've been struggling with this for hours. I'm obviously missing something completely.

I want to get some values out of TinyMCE textboxes, along with IDs. Then post these via ajax to the server.

jQuery 1.4 and JSON library are loaded

    var send_data = [];

     $('.contact_check').each(function (i, item) {
        var this_id = $(item).attr('id');
        var msgbox = tinyMCE.get('contacts['+this_id+'][message]');
        var content = addslashes(msgbox.getContent());
        send_data[i]["id"] = this_id;
        send_data[i]["content"] = escape(content);
      });

    var encoded = JSON.stringify(send_data);

   $.ajax({
      type: 'POST',
      url: 'http://localhost/test.php',
      data: encoded,
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      success: function(){alert('jay');}
    });

Firstly,

        send_data[i]["id"] = this_id;
        send_data[i]["content"] = escape(content);

does not seem to work. It says send_data[i] undefined. I've also tried:

send_data[this_id] = escape(content);

That does not seem to work either. The JSON string returns as []. What am I doing wrong?

+3  A: 

You're not really making a multi-dimensional array. You're making an array of objects. Either way, before you can set an attribute or array element of something at send_data[i], you have to make send_data[i] be something.

send_data[i] = {};
send_data[i]['id'] = this_id;
send_data[i]['content'] = escape(content);

or, better:

send_data[i] = {
  id: this_id,
  content: escape(content)
};
Pointy
A: 

You have to make each send_data[i] an object first:

 $('.contact_check').each(function (i, item) {
    var this_id = $(item).attr('id');
    var msgbox = tinyMCE.get('contacts['+this_id+'][message]');
    var content = addslashes(msgbox.getContent());
    send_data[i] = {};
    send_data[i]["id"] = this_id;
    send_data[i]["content"] = escape(content);
  });
txwikinger