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
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.
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
Related
I am new to codeignitor and trying to get jquery autocomplete from database . There are already many questions asked about this topic but none of those helped me.
Here is my script function from view file
View
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js">
</script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js">
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-
ui.css" />
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function() {
$( "#vname" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "vendor/search",
data: { term: $("#vname").val()},
dataType: "json",
type: "GET",
success: function(data){
var resp = $.map(data,function(obj){
return obj.tag;
});
response(resp);
}
});
},
minLength: 2
});
});
</script>
</head>
.
.
.
.
<input type="text" class="form-control" name="vendor_name" id="vname" />
here is controller(vendor) function (search) from which I am trying to get array of suggestion from database
Controller
public function search()
{
$json = [];
$this->load->database();
if(!empty($this->input->get("term"))){
$this->db->like('name', $this->input->get("term"));
$query = $this->db->select('id,name as text')
->limit(10)
->get("vendors");
$json = $query->result();
}
echo json_encode($json);
}
the problem is that when I type in input field, nothing happen (no autocomplete appears) but my vendor/search function is working fine while accessing it directly and pass something as parameter. I think $_GET[term] is always empty or something.
I dont have any idea what to do now any suggestion would be appreciable.
Change this line:
url: "vendor/search",
to:
url: "<?php echo base_url('vendor/search'); ?>",
Change in controller
public function search(){
$json = [];
$this->load->database();
if(!empty($this->input->get("term"))){
$this->db->like('name', $this->input->get("term"));
$query = $this->db->select('id,name as text')
->limit(10)
->get("vendors");
$json = $query->result();
}
//set page header
$this->output
->set_content_type('application/json')
->set_output(json_encode($json));
}
replace script tag
<script type="text/javascript">
$(function() {
$( "#vname" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "<?=base_url(); ?>vendor/search?term="+request.term,
dataType: "json",
type: "GET",
success: function(data){
response($.map(data, function (value, key) {
return {
label: value.text,
value: value.id
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
//select event of autocomplete
console.log("id : ",ui.item.value);
console.log("text : ",ui.item.label);
$('#vname').val(ui.item.label);
return false;
},
});
});
</script>
As i'm building an website that needs Ajax for sending POST methods without refreshing the entire page.
I tried using ajax to send data from an onclick event on an LINK-tag, but the ajax code does seem to send an EMPTY post.
This is the php/jquery/ajax code:
<p id="school_content">
</p>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".toggleThis").click(function(){
var Id = $(this).attr('id');
$.ajax({
contentType: "application/json; charset=utf-8",
url: "id_script.php",
type: "POST",
data: {
'school_name': Id,
},
success: function(data){
alert(Id);
},
});
$("#school_content").load("id_script.php");
});
});
</script>
The LINK-tag has the 'id' of the school of wich the information needs to be shown in the PARAGRAPH with 'id' "school_content" by this jquery part: $("#school_content").load("id_script.php"); .
The var Id = $(this).attr('id'); part works, because he's giving me the right school_name in an alert(); if I ask it to.
The id_script.php needs to get this POST in the usual way, but is does not..
The id_script.php code:
<?php
include('connect.php');
header('Content-Type: application/json');
if(isset($_POST['school_name'])){
$Id = $_POST['school_name'];
$extract = mysqli_query($con, "SELECT * FROM school_kaart WHERE school_name='$Id'");
$numro=mysqli_num_rows($extract);
if(mysqli_num_rows($extract) == '1'){
$row = mysqli_fetch_assoc($extract);
echo 'Yes it works!';
}
else{
echo 'Nope, didnt work!';
}
}
else{
echo 'Not posted!';
}
?>
I'm still getting "Not posted!" in the PARAGRAPH I mentioned earlier. What seems to be the problem?
.load is shorthand for an ajax request so you are actually doing 2 request.
The latter isn't sending any data and so it returns 'Not Posted!';
http://api.jquery.com/load/
try
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".toggleThis").click(function(){
var Id = $(this).attr('id');
$.ajax({
url: "id_script.php",
type: "POST",
data: {
'school_name': Id,
},
success: function(data){
alert(Id);
$("#school_content").html(data);
},
});
//remove this
//$("#school_content").load("id_script.php");
});
});
</script>
When I perform a simple ajax request I get the following error
TypeError: 'toString' called on an object that does not implement interface HTMLAnchorElement.
This is my ajax script
<script type="text/javascript">
$(document).on("ready", function(){
$("#tabla_persona table tr").click(function() {
var cod = $( "#identificador",this);
alert(cod.html());
var parametros={
"cod":cod
};
$.ajax({
type: 'POST',
url: '<?php echo site_url("archivo/prueba"); ?>',
data: parametros,
success: function(resp) {
$("#tabla_usuario_individual").html(resp);
}
});
});
});
</script>
This is my controller
public function prueba(){
$this->load->view('datos_persona');
}
and my simple page to see the result
<a>
Prueba
</a>
Try changing:
var parametros={
"cod":cod
};
to:
var parametros={
"cod":cod.html()
};
Just need simple change.I think the following code will work.
public function prueba(){
echo $this->load->view('datos_persona',true);
}
I'm struggeling with making an AJAX url inside of an php echo. Other troubleshooters around the internet didn't get me through it. Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup ({
cache: false
});
var ajax_load = "";
$( "#'.$row_items['id_aanbod'].'" ).change(function() {
$("#res").html(ajax_load).load("update.php", "e=" + $("#'.$row_items['id_aanbod'].'").val() & "id=" + $("#hrr").attr("id"));
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
The strange thing is that if I use only one variable the script works like it should, but as soon as I insert the second part there is nothing happening. Can anyone help me with this?
& "id="
should be
+ "&id="
But for clean code, you could write like below:
$("#<?php echo $row_items['id_aanbod']?>").change(function() {
$("#res").html(ajax_load).load("update.php", {
e: this.value,
id: $("#hrr").attr("id")
});
});
Please try like this:
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup ({
cache: false
});
var ajax_load = "";
$( "#<?=$row_items['id_aanbod']?>" ).change(function() {
$("#res").html(ajax_load).load("update.php", "e="+$("#<?=$row_items['id_aanbod']?>").val() + "&id=" + $("#hrr").attr("id"));
});
});
Don't forget to check vals. If short open tags is OFF -> then try :
<?php echo $row_items['id_aanbod']?>
wonder if anyone can help; I'm trying to implement some ajax through jquery onto a form in a wordpress template.
The jquery is working, and the I can log a console message in the sucess: section, but the data is 0, when it should be calling the php function (at the moment on the same page, and I can call this directly)
so I guess the jquery is working, the admin-ajax is being called, its just the php function is not being called. Any ideas what I could be doing wrong ? I don't fully understand hooks, so perhaps that is an issue - that I need to hook something in somewhere?
jquery (domain would replace comments)
<script type="text/javascript">
jQuery(function ($) {
$( "#movies" ).autocomplete({
minLength:2,
delay:500,
source: function( request, response ) {
$.ajax({
type: 'POST',
url: "http://<!--domain here -->/wp-admin/admin-ajax.php",
dataType: 'json',
data: {
action: 'getMoviesForCode',
searchString: $("#movies").val()
},
success: function( data ) {
response(data);
console.log('jjj'+data);
}
});
}
});
});
</script>
php function (on same page)
<?php
function getMoviesForCode(){
echo "
<script type=\"text/javascript\">
alert(\"hh\");
</script>
";
$searchString = $_POST['searchString'];
$results = va_getMoviesForCode($searchString);
$results = json_encode($results);
die($results);
}
?>
Thanks,
You're doing it wrong. You php function should be in your theme's functions.php file.
You should then hook the function to wp_ajax_[your_action] and wp_ajax_nopriv_[your_action].
Example of what should be in your functions.php :
function getMoviesForCode(){
echo "
<script type=\"text/javascript\">
alert(\"hh\");
</script>
";
$searchString = $_POST['searchString'];
$results = va_getMoviesForCode($searchString);
$results = json_encode($results);
die($results);
}
add_action('wp_ajax_getMoviesForCode', 'getMoviesForCode');
add_action('wp_ajax_nopriv_getMoviesForCode', 'getMoviesForCode');