I'm new in codeigniter and using such as javascript, jQuery, Ajax, etc. Just now, i'm trying to build an application like visitor management system, that usually takes barcode.
Here's my table on database:
Here's my model:
public function selectX($tbl, $where)
{
return $this->db->get_where($tbl, $where);
}
Here's my controller:
public function check_av_vin(){
$vin = $this->input->post('f1');
$where = array('Vin'=>$vin);
$result = $this->crud_m->selectX('tbl_vin', $where);
if($result->num_rows() > 0){
echo "1";
}else{
echo "0";
}
}
Here's my view:
<input class="form-control" type="text" name="f1" id="barcode" autofocus></input>
Here's my JS (on the same view):
$(document).ready(function() {
$("#barcode").on('keydown', function(event) {
if (event.keyCode == 13) {
var bc = $("#barcode").val();
$.ajax({
url: "<?php echo site_url('Lobby/check_av_vin')?>",
data: {Vin : bc},
type: 'POST',
success: function(data){
if(data == '1'){
alert("VIN Already Exist!");
$("#barcode").val("");
$("#barcode").focus();
}
else if(data == '0'){
alert("VIN available!");
$("#barcode").val("");
$("#barcode").focus();
}
else{
alert("Error");
$("#barcode").val("");
$("#barcode").focus();
}
}
});
$("#name").focus();
return false;
}
});
The question is: Whatever i'm inserting the correct barcode like 'VIN00001' or wrong barcode or not inserting any text and hit enter, its always get data with string '0' and always get alert 'VIN available'. I dont know where's the problem. Please help me.
you're sending data via Ajax, and the data youre sending is { Vin : whatever }
so to get this in your function check_av_vin() you need :
$vin = $this->input->post('Vin'); instead of $vin = $this->input->post('f1');
You have wrong variable name in your code.
in check_av_vin() function you used
$this->input->post('f1');
though in form the input name is f1, when you send your ajax request you put
data: {Vin : bc},
just put following will solve your problem.
$this->input->post('Vin');