i have a problem when i am trying to create a autocomplete with dynamic value that based on combobox using codeigniter, i have tried using ajax and no success.
here is my ajax code for calling item in category
<script type="text/javascript">
$(document).ready(function() {
$("#jenis").change(function(){
$.ajax({
type : "POST",
url: "<?php echo base_url(); ?>whz/admin/get_item",
dataType: "html",
data : "item=" + $("#jenis").val(),
success: function(data)
{
$("#showitem").text(data);
}
});
});
});
</script>
this is my autocomplete jquery code
<div id="showitem">
<script>
$(function() {
var availableTags = [
<?php foreach ($item as $row){
echo '"'.$row->item_name.'",';}?>
];
$( "#autotags" ).autocomplete({
source: availableTags
});
});
</script>
</div>
and here is my controller
public function get_item()
{
$this->load->model('whz_model');
$category = $this->input->post('item');
$item=$this->whz_model->get_item_by_cat($category);
$script = '
$(function() {
var availableTags = [';
foreach ($item as $row)
{
$script .= '"'.$row->item_name.'",';
}
$script .= '];
$( "#autotags" ).autocomplete({
source: availableTags
});
});';
echo $script;
}
i am considering using json as another option, but i still don't have enough experience using it.
sorry for bad english, thanks for your help
i already fix it with another method i found in the internet, it might be not the best but it works with me, here is the link
http://www.danielrosca.ro/blog/en/codeigniter-autocomplete/
thank you for all of your answer
This is only based on documentation because I don't have any system handy where I could try.
You are telling jQuery that your AJAX response is "html"
which means the JavaScript you load will never be executed, I believe. Possibly, it would work if you loaded the data as "script"
but the better way would indeed be to use JSON.
Your AJAX call would then look like this:
<script type="text/javascript">
$(document).ready(function() {
$("#jenis").change(function(){
$.ajax({
type : "POST",
url: "<?php echo base_url(); ?>whz/admin/get_item",
dataType: "json",
data : "item=" + $("#jenis").val(),
success: function(data)
{
availableTags = data;
}
});
});
});
</script>
with a controller like that:
public function get_item()
{
$this->load->model('whz_model');
$category = $this->input->post('item');
$item=$this->whz_model->get_item_by_cat($category);
$this->output
->set_content_type('application/json')
->set_output(json_encode($item)));
}
You will have to expose the variable availableTags
globally for this to work which you can achieve by changing your DOM to
<div id="showitem">
<script>
$(function() {
availableTags = [
<?php foreach ($item as $row){
echo '"'.$row->item_name.'",';}?>
];
$( "#autotags" ).autocomplete({
source: availableTags
});
});
</script>
</div>
You might also want to expose it as window.availableTags
, so you can check it's value in your browser's console.
As mentioned at the start, I did not test this but I believe it should work.