I am Facing Problem in Retrieving the Data from checkbox in codeigniter. My view is
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
var base_url = '<?=base_url()?>';
function test()
{
var country = document.forms["fetch_country"].country;
var countryText = ''
for (i=0;i<country.length;i++)
{
if (country[i].checked)
{
countryText = countryText + country[i].value + ","
}
}
// alert(countryText)
var type= countryText;
// alert (type);
$.ajax({
url: base_url+'/index.php/ajax_test/index',
type : 'POST', //the way you want to send data to your URL
data : {'type' : type},
success : function(result){ //probably this request will return anything, it'll be put in var "data"
alert (type);
$('#div1').html(result); //jquery selector (get element by id)
}
});
// alert ("countryFinalValue is " + id);
}
</script>
</head>
<body>
<form id="fetch_country">
<div id="new">
<input id="country" type="checkbox" onclick="test()" value="1">India<br/>
<input id="country" type="checkbox" onclick="test()" value="2">USA<br/>
<input id="country" type="checkbox" onclick="test()" value="3">UK<br/>
<input id="country" type="checkbox" onclick="test()" value="4">China<br/>
</div>
</form>
<div id="div1"></div>
</body>
AND My Controller is :
<?php
class ajax_test extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->view('view_test');
}
public function index()
{
//$this->load->view('view_test');
$id = $this->input->post('type');
echo $id;
//$this->load->view('view_test' , $id );
}
}
?>
The Problem I am facing is I am getting the value of checked checkbox, but with value I am getting whole set of checkbox repeated in my view .
please have your list generate like this
<input id="country" type="checkbox" data-value="1">India<br/>
<input id="country" type="checkbox" data-value="2">USA<br/>
<input id="country" type="checkbox" data-value="3">UK<br/>
<input id="country" type="checkbox" data-value="4">China<br/>
your testing controller is fine for now but later add this to constructor
public function __construct() {
parent::__construct();
if (!$this->input->is_ajax_request()) {
redirect(); //make sure that user is redirected when request is not AJAX
}
$this->output->enable_profiler(FALSE); //force to disable profiler
}
your javascript file should look lot a like also define base_url somewhere on top of your page
$(document).ready(function(){
$('#country').click(function() {
var value = $(this).data("value");
$.ajax({
type : 'POST', //Method type
url : base_url + '/index.php/ajax_test/',
data : {type: value}, //post data
success : function(data) {
console.log(data);
}
});
});
});