2

I am having trouble passing javascript arrays and other variables to my php controller. I am doing this in codeigniter. I have assigned some values on javascript like this:

var count = ($('#listOfProducts tr').length);
//loop start
var i=0;
grid=$('#listOfProducts input[type="checkbox"]:checked').each(function(){
    var $row = $(this).parents('tr'); 
    var $trid =$(this).closest('tr').attr('id');
    rowid[i]=$trid; 
        rowfields.push({itemname: $row.find('td:eq(0)').text(), productname:$row.find('td:eq(1)').text(), productdesc: $row.find('td:eq(2)').text(), unitprice:$row.find('td:eq(3)').text(), quantity:$row.find('td:eq(5) input').val(), amount:$row.find('td:eq(6) input').val()});
    i++;
});

i have to pass it to my controller so i could save the values to my database... Any help? I am thinking of storing this array as a session variable but I do not know how, considering the client-side and server-side issues.

Umpong_1947676
  • 111
  • 2
  • 15

2 Answers2

2

I use CI and the best way I found is to send it thru AJAX, like this:

$('.your-element').click(function(e){
    var id = 1;
    $.ajax({
        url: base_url()+'yourController/youFunction/'+id,
        type: 'get',
        dataType: 'html',
        success: function(html) {
            //YOUR ACTION
        }
    });

});

Let us know if you need more specifications. NOTE: This method creates problems if you have sessions data going on as every ajax call changes the session id or doubles the time of the session_update. To handle this see this post: HANDLING CODEIGNITER SESSION/AJAX PROBLEMS

Edit:

For the base_url() in JS I wrote this in the index.php file:

<script>
function base_url(){
  var url  = '<?= base_url() ?>';
  return url;
}
</script>

Array Edit

For an Array ajax-call I'd do it using jQuery $.post(), like this:

$('.your-element').click(function(e){
    e.preventDefault();
    var demoArray = ['1', '3', '7'];
    $.post(base_url()+'admin/test/', {array_send:demoArray}, function(result){
        alert(result);
    });
});

Where the controller admin/testis:

public function test(){
    print_r($_POST['array_send']);
}
Community
  • 1
  • 1
Mr.Web
  • 6,992
  • 8
  • 51
  • 86
1

There are actually only a few options to pass information from javascript (or the browser that is) to php:

  1. Using an Ajax request. This can be both a GET or a POST request (variables in php residing in the $_GET or $_POST array respectively
  2. Using a form: add the data you want to send to a oldschool html form and post it.
  3. By magic: put a toothbrush against your head, turn around 7 times and murmur some non-existent words. It might help.
giorgio
  • 10,111
  • 2
  • 28
  • 41