title: Using AJAX to pass javascript array to CodeIgniter controller
body: <p>I am creating a simple javascript array variable, and I want to pass that array to a CI controller function using jQuery Ajax.</p>
  
  <p>Unlike the many questions on this subject, the array does not originate from a form, and it's not any kind of dom element. I hope this question is not identical to anything else that's been asked on SO. Here's my js code:</p>
  
  <pre><code>function processImagesList(){
    var files = new Array();
    var i = 0;
    $("#thumbs li").each(function() {
       var source = $('img', this).attr('src');
       var f = source.split("/");
       var file = f[f.length - 1];
       files[i] = file;
       i++;    
    });
    if(files.length &gt; 0){
      url = "/ajax/add_images_to_asset/";
      var formData = JSON.stringify( files );
      $.ajax({
          method: "POST",
          url: url,
          data : formData,
          dataType: "json"
      }).done(function( data ) {
          $.each(data,function(k,v){ alert(k + " = " + v); });
      }).fail(function(jqXHR, textStatus){
          alert( "Error: " + jqXHR.status + " , " + jqXHR.responseText );
      });
    }
  }
  </code></pre>
  
  <p>This basically reads the src of the img tag within an li item, and parses the src string to strip out the relative url of the image, then derive the pure filename of the image.</p>
  
  <p>Next, I store the filename in an array called "files".</p>
  
  <p>Next, I want to pass this array to my CI controller using Ajax.</p>
  
  <p>I've tried <code>var formData = JSON.stringify( files );</code>.
  I've tried <code>var formData = $( files ).serialize();</code>.
  I've tried <code>var formData = $( files ).serializeArray();</code>.
  I've tried sending as method: 'POST';
  I've tried sending as method: 'GET';</p>
  
  <p>Here's my controller code:</p>
  
  <pre><code>public function add_images_to_asset()
  {
      $data = array();
      foreach($_POST as $k=&gt;$v){
          //$data["$k"] = $v;
          echo $k . " = " . $v . "&lt;br&gt;";
      }
      header('Content-Type: application/json');
      echo json_encode($data);
  }
  </code></pre>
  
  <p>Obviously I'm trying to echo out the POST (or even GET) data before the JSON header, but that's ok. No matter what I use, there doesn't seem to be any data (no data makes it to the CI controller function, no matter whether I use the POST or the GET method in Ajax &amp; controller).</p>
  
  <p>The URI is: <code>console/read_pictures_table</code></p>