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.
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/test
is:
public function test(){
print_r($_POST['array_send']);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments