autocomplete in codeigniter not displaying anything - javascript

Hy, i am making an autocomplete search field in codeigniter,I tried to do autocomplete in codeignter using the below code .But it is not working for me.Not displaying anything in the autocomplete text field.Can anyone find the problem
success function of data displaying as undefined
Here is my view:
View
<script >
$(document).ready(function() {
$("#trackerid").change(function(){
var var_locoid= $("#trackerid option:selected").val();
alert(var_locoid);
$( "#deliverylocation" ).autocomplete({
source: function(request, response) {
var auto_data= $("#deliverylocation").val();
alert(auto_data);
//alert(var_locoid);
$.ajax({
url:"http://localhost/testcontroller/test/lookup",
type:"POST",
datatype:'json',
data:{'var_locoid' :var_locoid,'auto_data':auto_data},
success: function(data){
response(data);
alert(data);
}
});
},
minLength: 1
});
});});
</script>
<input type="text" name="deliverylocation" id="deliverylocation" placeholder="Enter your area " >
Controller
function lookup()
{
$citys = $this->input->post('var_locoid');
$auto_text = $this->input->post('auto_data');
//var_dump($citys);
//$data['response'] = 'false';
$place = $this->Demo_model->load_places($citys,array('keyword' => $auto_text));
$json_array = array();
foreach ($place as $row){
array_push($json_array, $row->locationtext);
}
//echo json_encode($place);
echo json_encode($json_array);
}
Model
function load_places($citys,$auto_text)
{
//$this->db->select('locationtext');
$this->db->select('locationtext');
$this->db->like('locationtext', $auto_text);
$this->db->from('tbl_location');
$array = array('cityautocode' => $citys);
$this->db->where($array);
//$this->db->->where('cityautcode', $place);
$query= $this->db->get();
//echo $this->db->last_query();
return $query->result();
}

I am using an autocomplete pattern from https://www.devbridge.com/sourcery/components/jquery-autocomplete/
Here is my controller:
$arrayData = $this->CRUD_model->getSelect("id as data, name as value, purchase_price","articles")->result_array();
echo json_encode($arrayData);
And my views:
$(document).ready(function(){
// $("body").addClass("sidebar-collapse");
var dataArticles = $.parseJSON(getArticles());
$("input[name='articles_name']").devbridgeAutocomplete({
lookup: dataArticles,
onSelect: function(suggestion) {
$("input[name='articles_id']").val(suggestion.data);
},
showNoSuggestionNotice: true,
noSuggestionNotice: 'Barang tidak ditemukan',
noCache: true,
minChars: 2,
})
})
function getArticles(){
result = null;
$.ajax({url: '<?= base_url();?>panel/purchasing/request/getArticles',type: 'get',dataType: 'html',async: false,success: function(data) {result = data;} });
return result;
}
For this example I use lookup, so all autocomplete values loaded when I open the page, note that id must be named "data" and label must be named "value".

Related

submit form to check something with ajax and jquery

I am making a form to check a security code. In fact, I am new to ajax and jquery, so I tried what I can, but my code doesn't work. Can anybody help me?
php file :
<?php
include('/includes/db-connect.php');
if( isset($_POST["seccode"]) ){
$result=mysqli_query($con,"SELECT * FROM `certificate_acheived_tbl` WHERE `cert_check_code` = ".$seccode.")";
if( mysql_num_rows($result) == 1) {
echo "<script>alert('s')";
}
}
?>
js file:
$(function() {
$(".btn btn-success").click(function() {
var ID = $(this).attr('id');
$.ajax({
type: "POST",
url: "cert-check-ajax.php",
data: 'certcode='+ ID,
success: function() {
$('#someHiddenDiv').show();
console.log();
}
});
});
});
your code is bad... (sometimes mine too)
One first mistake : data: 'certcode='+ ID, in jQuery
and isset($_POST["seccode"]) in PHP 'certcode' != 'seccode'
so a better code.. ?
jQuery (I allways use JSON, it's more easy)
$(function () {
$(".btn btn-success").click(function() {
var
Call_Args = {
certcode: $(this).attr('id')
};
$.ajax({
url: 'cert-check-ajax.php',
type: 'POST',
data: Call_Args,
cache: false,
dataType: 'json',
success: function (data) {
console.log( data.acceptCod ); // or data['acceptCod'] if you want
$('#someHiddenDiv').show();
// ...
}
}); //$.ajax
}); // btn btn-success").click
});
PHP (with utf8 insurance, and good header / JSON encode response )
<?php
mb_internal_encoding("UTF-8");
include('/includes/db-connect.php');
$T_Repons['acceptCod'] = "bad";
if (isSet($_POST['certcode'])) {
$sql = "SELECT * FROM `certificate_acheived_tbl` ";
$sql .= "WHERE `cert_check_code` = ".$_POST['certcode'].")";
$result = mysqli_query($con, $sql);
$T_Repons['acceptCod'] = (mysql_num_rows($result) == 1) ? "ok" : "bad";
}
header('Content-type: application/json');
echo json_encode($T_Repons);
exit(0);
?>
you can use it
$(function() {
$(".btn btn-success").click(function() {
var ID = $(this).attr('id');
$.ajax({
type: "POST",
url: "cert-check-ajax.php",
data: {'seccode': ID}
}).done(function(data) {
$('#someHiddenDiv').show();
console.log(data);
});
});
});

how can i insert database record when a button is clicked - Codeigniter, jquery, ajax

so here is my problem, i am creating my own upvote and downvote feature in my school project. All i want to happen is when I click an arrow-up image, it will insert a record to database. It will add a one record to upvote table in my database.
<script type="text/javascript">
$( document ).ready(function() {
$("#try").click(function(){
var username = $("#username").val();
var thread_id = $("#thread_id").val();
var vote = $("#vote").val();
$.ajax(
{
type:"post",
url: "<?php echo site_url();?>/Users/add_vote/",
data:{ username:username, thread_id:thread_id, vote:vote},
success:function(data)
{
alert("POST SUBMITTED");
}
});
});
});
and here is my form
<div id = "active_upvote_div">
<form>
<input type="hidden" name = "username" id="username" value= "try">
<input type="hidden" name="thread_id" id="thread_id" value= "1">
<input type="hidden" name="vote" id="vote" value= "1">
<button type="submit" id="try"><img src="<?php echo base_url();?>/public/images/upvote.png" height:"25px" width="25px"/> </button>
</form>
</div>
My Controller only calls the model
This is my Model
public function ajax()
{
$add_user = array(
'username' => $this->input->post('username'),
'thread_id' => $this->input->post('thread_id'),
'vote' => $this->input->post('vote'),
);
$this->db->insert('thread_upvote', $add_user);
}
hoping for an immediate response :(
In codeigniter $this->input->post() is equivalent to $_POST which makes array of posted names as key/value pair.
In your controller's add_vote() function do this...
public function add_vote()
{
$data = $this->input->post();
$this->load->model('model_namel');//loads model
$this->model_name->ajax($data);//call model's function with data
}
Then in model's ajax() function
public function ajax($data=array())
{
$this->db->insert('thread_upvote', $data);// inserts into database
}
In your Ajax:
$( document ).ready(function() {
$("#active_upvote_div").click(function(){
var username = $("#username").val();
var thread_id = $("#thread_id").val();
var vote = $("#vote").val();
$.ajax({
type:"POST",
dataType: 'json', //add this to call json
url: "<?php echo site_url();?>/Users/add_vote/",
data:{ username:username, thread_id:thread_id, vote:vote},
success:function(data)
{
if(data.success == true){
alert("POST SUBMITTED");
} else{
alert("Failed to Post");
}
}
});
});
});
In your Controller:
Class Users extends CI_Controller{
public function add_vote()
{
$result = $this->name_of_model->ajax(); //call the ajax function in you model
echo json_encode($result); //check the return if true or false and pass to json
}
}
In your Model:
public function ajax()
{
$add_user = array(
'username' => $this->input->post('username'),
'thread_id' => $this->input->post('thread_id'),
'vote' => $this->input->post('vote'),
);
if($this->db->insert('thread_upvote', $add_user))
{
return true;
} else{
return false;
}
}

Update select options based on other selected option from database

I have a form which selects regions, provinces, and cities. The select options for provinces depends on the selected region and the options for cities depends on the selected province. All the options are from the database
I have already made the region show up with this code.
<select class="form-control" id="region" name="region">
<?php
if( isset($Region) && count($Region)>0 ){
foreach($Region as $Region){
echo '
<option>'.$Region['region'].'</option>
';
}
}else{
echo '
<option>NO RECORDS FOUND</option>
';
}
?>
</select>
Could you please help me on my next step which is to display the options for provinces?
<select class="form-control" id="province" name="province">
</select>
I believe after achieving this step I would be able to do the same for displaying cities. Thank you!
Database name: patrol
table name: geography
>id
>region
>province
>city
I've tried the same as this one by putting this script
<script>
$(function() {
$(document).ready(function () {
$('#region').change(function() {
var select = $('#province').empty();
$.get('script.php', {region: $(this).val()}, function(result) {
$.each(result, function(i, item) {
$('<option value="' + item.value + '">' + item.name + '</option>').
appendTo(select);
});
});
});
});
});
</script>
and having this script.php
<?php
if (isset($_GET['region'])) {
$sql = new mysqli('localhost','root','','patrol');
$region = mysqli_real_escape_string($sql,$_GET['region']);
$query = "SELECT * FROM geography WHERE region = $region";
$ret = $sql->query($query);
$result = array();
while ($row = $ret->fetch_assoc()) {
$result[] = array(
'value' => $row['id'],
'name' => $row['province']
);
}
echo json_encode($result);
}
?>
<option>'.$Region['region'].'</option>
You did not set any value in region select option.
It should be like below:
<option value="'.$Region['region'].'">'.$Region['region'].'</option>
also use console.log(result) to see you are getting expected data back or not.
Thank you for answering guys. However, I have found an answer and it did the fix. I'll post the script for others who have the same question as mine
<script type="text/javascript">
$(document).ready(function()
{
$("#region").change(function()
{
var region= document.getElementById("region").value;
var dataString = 'region='+ region;
$.ajax
({
type: "POST",
url: "get_province.php",
data: dataString,
cache: false,
success: function(html)
{
$("#province").html(html);
}
});
});
$("#region").change(function()
{
var province= document.getElementById("province").value;
var dataString = 'province='+ province;
$.ajax
({
type: "POST",
url: "get_city.php",
data: dataString,
cache: false,
success: function(html)
{
$("#city").html(html);
}
});
});
$("#province").change(function()
{
var province= document.getElementById("province").value;
var dataString = 'province='+ province;
$.ajax
({
type: "POST",
url: "get_city.php",
data: dataString,
cache: false,
success: function(html)
{
$("#city").html(html);
}
});
});
});
</script>

Pass values from JQUERY to PHP then output to INPUT in FORM

i need to get a value from the a form then send it to php using jquery then output the result a dropdown select menu
get the value of using jquery
<input id="search" name="search" type="text">
send it to php and perform a query
<select id="farmertype" name="farmertype" >
<option value="" > - PLEASE SELECT FARM -</option>
//// output here as options
</select>
my php file farm.php
<?php
include_once("../init.php");
$q = ($_POST["search"]);
$db->query("SELECT * FROM farmers ");
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
echo "<option value='$idno'>$idno</option>";
}
}
?>
the jquery part is so messy this is where i really need help
$("#search").click(function() {
search = $(this).attr('#search');
$.ajax({
type: 'GET',
url: 'farm.php',
data: "#search=" + search,
});
});
try this, it will help you.
JQuery:
$("#search").click(function() {
search = $(this).val();
$.ajax({
type: 'POST',
url: 'farm.php',
data: {searchValue:search},
success:function(result) {
console.log(result);
}
});
});
PHP:
<?php
include_once("../init.php");
$q = ($_POST["searchValue"]);
$db->query("SELECT * FROM farmers");
$result = [];
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
$result = "<option value='$idno'>$idno</option>";
}
print_r($result);
?>
what is the purpose of your variable $q?
Your jquery can be like :
$("#search").click(function() {
search = $('#search').val();
$.ajax({
type: 'GET',
url: 'farm.php',
data: {search : search},
success: function(html){
alert(html);
}
});
});
$("#search").click(function() { /* I think you should use keyUp or use click on a button, nobody clicks an input box */
var search = $(this).val();
$.ajax({
method: 'POST', //
url: 'farm.php',
data: {'search' : search},
success: function(data){
alert(data);
}
});
});

jquery call other self-declared function in autocomplete select event

Can I call a function in autocomplete select event?
I have a function call getResult() which will retrieve data from database, the function is working smooth, just I fail to call this function in autocomplete's select event. Below is my code:
Auto-complete code:
$(function()
{
//auto complete for facultyID
var availableTags = <?php
$sql = "SELECT FacultyID from tblfaculty";
$result = mysql_query($sql, $DBLink) or die("Error " . mysql_error($DBLink));
$id_list = array();
while($row = mysql_fetch_array($result))
{
$id_list[] = $row['FacultyID'];
}
echo json_encode($id_list); ?>;
$("#FacultyID").autocomplete(
{
source: availableTags,
autoFocus:true,
select: function(event, ui)
{
getResult();
}
});
});
getResult() function:
function getResult()
{
$(function()
{
var Semester = $('#Semester').val();
var Year = $('#Year').val();
var Course = $('#Course').find(":selected").val();
var Subject = $('#Subject').find(":selected").val();
var FacultyID = $('#FacultyID').val();
var TimeSlot = $('#TimeSlot').val();
var Location = $('#Location').val();
$.ajax(
{
type: 'POST',
url: 'ajax_get_time_table.php',
data: {Semester:Semester+", "+Year, Course:Course, SubjectID:Subject, FacultyID:FacultyID, TimeSlot:TimeSlot, Location:Location},
dataType: 'json',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
//do something
}
else
{
//do something
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
});
}
Is there any wrong with my code?
You don't have to put everything in a doc ready block in getResult() function:
$(function(){});
because the DOM is already loaded and you are able to call this function inside autocomplete's select event.

Categories

Resources