I am now working in a POS System. My goal is, as the input is getting updated by the "keyup", the results that match this keyup show in a table.
Something like this:
Example
I think I have the code completed, just missing to echo the results in a table. This is my actual JS code:
$(document).ready(function(){
$("tablaClientesEnVenta").dataTable({
bFilter: false, bInfo: false
});
$("#inputNombreCliente").on('keyup', function(){
$("#tablaClientesEnVenta").css("visibility", "visible");
if (!$("#inputNombreCliente").val()){
$("#tablaClientesEnVenta").css("visibility", "hidden");
}
console.log("tecla detectada");
var nombreCliente = $(this).val();
console.log(nombreCliente);
var datos = new FormData();
datos.append("nombreCliente", nombreCliente);
$.ajax({
url:'ajax/crear-venta.ajax.php',
method: "POST",
data: datos,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success:function(respuesta){
console.log(respuesta);
}
});
});
});
This is my AJAX Code to call the function:
<?php
require_once '../controladores/clientes.controlador.php';
require_once '../modelos/clientes.modelo.php';
class AjaxVentas{
public $nombreCliente;
public function ajaxNombreCliente(){
$item = "nombre";
$valor = $this->nombreCliente;
$respuesta = ControladorClientes::ctrMostrarAjaxClientes($item,
$valor);
echo json_encode($respuesta);
}
}
if (isset($_POST['nombreCliente'])) {
$cliente = new AjaxVentas();
$cliente -> nombreCliente = $_POST['nombreCliente'];
$cliente -> ajaxNombreCliente();
}
This is the function that calls out for the model:
static public function ctrMostrarAjaxClientes($item, $valor){
$tabla = "clientes";
$respuesta = ModeloClientes::mdlMostrarAjaxClientes($tabla, $item,
$valor);
return $respuesta;
}
Finally, the function that calls out the data from the DB:
static public function mdlMostrarAjaxClientes($tabla, $item, $valor){
$statement = Conexion::conectar()->prepare("SELECT * FROM $tabla
WHERE $item = :item");
$statement->execute(array(":item" => $valor));
return $statement->fetchAll();
}
As a conclusion, I would like to know what I am missing, since the console.log(respuesta) in the JS is giving me an error. Thank you and have a nice day!
In your AjaxVentas class;
ControladorClientes::mdlMostrarAjaxClientes($item, $valor);
The static method requires 3 arguments ($table, $item, $valor) not two($item, $valor) being passed above
Edited
Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :item");
Table name is not being passed
Related
Plz check this jsfiddle. My results are like this,
http://jsfiddle.net/kz1vfnx2/
i need to store these datas to database(sql server) one by one in each row using PHP Codeigniter. Insert to table looks like
Date Frequency
05-Feb-2019 1st Basic Treatment
12-Mar-2019 2nd Control Treatment
----------------------------------
--------------------------------
when button clicks call the function and insert to datatabase
$('#saveactivityarea').on('click', function(event) { //save new activity area
var act_contractbranch_firstjobdt = "2019-01-01";
var Contractend_firstjobdt = "2020-01-01";
var act_job_freq_daysbtw= "30";
saveschedule(act_contractbranch_firstjobdt,Contractend_firstjobdt,act_job_freq_daysbtw,0);
var contractID = $('#contractID').val();
var act_job_freq_contract = $("#act_job_freq_contract option:selected").val();
$.ajax({
type: "POST",
url: 'activity_submitted',
data: {
//here i need to pass date and frequency. insert to table like one by one row
getcontract_id: contractID,
getcontractbranch_firstjobdt: act_contractbranch_firstjobdt,
//etc....
},
success: function(data) {
alert('success')
}
})
PHP MODAL FUNCTION
$data_jobschedule = array(
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq')
);
$insert_id = 0;
if ($this->db->insert("job_schedule", $data_jobschedule))
$insert_id = $this->db->insert_id();
}
Please find the jQuery Ajax code here
Inside while loop
var dataArray = [];
while(condition) {
details = [];
//do your calculations
details['date'] = date;
details['frequency'] = frequency;
dataArray[] = details;
}
$.ajax({
url: "<?php echo site_url('activity_submitted'); ?>",
data: {dateArray: dataArray},
success: function(data){
alert('success');
},
error: function() { alert("Error."); }
});
In the controller and model, you need to get the data and insert it into the table.
$data = $_REQUEST['dateArray'];
$this->db->insert_batch('mytable', $data);
When a build name is clicked the inner html is passed into a JavaScript variable loadDump then passed over to PHP.
$.ajax({
url:"http://custom-assembly.tcad.co.uk/wp-content/themes/custom-assembly/grp-enclosure/load.php",
method: "post",
data: { loadDump: JSON.stringify( loadDump )},
success: function(res){
var key_map_obj = '<?php echo $key_map_loaded; ?>';
console.log(key_map_obj);
var key_map_obj_string = key_map_obj;
localStorage.setItem("key_map_obj_string", key_map_obj_string);
console.log(localStorage);
}
})
Once this happens the php in load.php executes. The loadDump variable is used in a sql query to find the matching field.
$loadDump = wp_unslash( $_POST['loadDump'] );
$table_name= $wpdb->prefix. 'product_configurator';
$DBP_results= $wpdb->get_results("SELECT * FROM $table_name WHERE keymap_key = $loadDump");
$DBP_current_user = get_current_user_id();
foreach($DBP_results as $DBP_cols){
$user_id= $DBP_cols->user_id;
$enclosure_type= $DBP_cols->enclosure_type;
$keymap_key= json_decode($DBP_cols->keymap_key, true);
$key_map_loaded=json_decode($DBP_cols->key_map, true);
}
?>
How can i get $key_map_loaded to pass to the JavaScript and save in the local storage using Ajax.
In you php file try to return the result :
e loadDump variable is used in a sql query to find the matching field.
$loadDump = wp_unslash( $_POST['loadDump'] );
$table_name= $wpdb->prefix. 'product_configurator';
$DBP_results= $wpdb->get_results("SELECT * FROM $table_name WHERE keymap_key = $loadDump");
$DBP_current_user = get_current_user_id();
foreach($DBP_results as $DBP_cols){
$user_id= $DBP_cols->user_id;
$enclosure_type= $DBP_cols->enclosure_type;
$keymap_key= json_decode($DBP_cols->keymap_key, true);
$key_map_loaded=$DBP_cols->key_map;
}
echo $key_map_loaded;
?>
Then in the JavaScript receive it for the ajax request:
$.ajax({
url:"load.php",
method: "post",
data: { loadDump: JSON.stringify( loadDump )},
success: function (data) {
var key_map_obj = data;
console.log(key_map_obj);
var key_map_obj_string = (key_map_obj);
localStorage.setItem("key_map_obj_string", key_map_obj_string);
console.log(localStorage);
},
})
Parameters are not being passed to the model, so the sql query is not yielding results. It just shows nothing, not even errors. Why are not the parameters being passed to the model?The sql query in the database works correctly, the date before the variables is to ignore the time, since in the database the field is of type datetime
Controller
function __construct()
{
parent::__construct();
$this->load->model('M_Login');
$this->load->model('M_Porcentaje');
}
public function tabla_porcentaje(){
$fecha_ini = $this->input->post('fecha_ini');
$fecha_ter = $this->input->post('fecha_ter');
$data['consulta'] = $this->M_Porcentaje->tabla_porcentaje($fecha_ini, $fecha_ter);
$this->load->view('usuarios/test.php',$data);
}
Model
public function tabla_porcentaje ($fecha_ini, $fecha_ter){
$this->db->select("motivos_citas.descripcion_mot,COUNT(*) AS cantidad_motivos, (SELECT COUNT(motivos_citas.descripcion_mot)* 100 / COUNT(citas.id_ci) FROM citas AS citas WHERE date(citas.fecha_ini) BETWEEN date('$fecha_ini') AND date('$fecha_ter') ) AS porcentaje");
$this->db->from("citas");
$this->db->join("motivos_citas","citas.id_mot=motivos_citas.id_mot");
$this->db->where("date(citas.fecha_ini) BETWEEN date('$fecha_ini') AND date('$fecha_ter') ");
$this->db->group_by("motivos_citas.descripcion_mot");
$consulta = $this->db->get();
return $consulta->result();
}
AJAX
<script>
$(document).ready(function(){
$("#btn_buscar").click(function(evento){
var fecha_ini = $("#fecha_ini").val();
var fecha_ter = $("#fecha_ter").val();
$.ajax({
url: "<?php echo base_url();?>C_Porcentaje/tabla_porcentaje/",
type: 'post',
data: { "fecha_ini": fecha_ini, "fecha_ter": fecha_ter },
success: function(response){
alert($("#fecha_ini").val());
alert($("#fecha_ter").val());
window.open('<?php echo base_url();?>C_Porcentaje/tabla_porcentaje/', '_blank');
}
});
});
});
</script>
Your binding is not okay. You should use :
$(document).on('click', '#buscar',function(url){
Try using json_decode(file_get_contents("php://input")) rather than $this->input->post() if the controller will read the data.
public function tabla_porcentaje(){
$input_post = json_decode(file_get_contents("php://input"));
$data = array (
'fecha_ini' => $input_post->fecha_ini,
'fecha_ter' => $input_post->fecha_ter
);
$this->load->model('M_Porcentaje_PDF');
$this->M_Porcentaje_PDF->tabla_porcentaje($data);
}
here is an issue that I am facing. As you can see in the question I need to get the customer details of a particular customer when their surnames are common.
Currently on selecting the customer's surname I get a popup with the list of all common surnames. While selecting a particular customer I get some completely different customer details.
I am using codeigniter. I will post my code of the mvc below. Any help will be greatly appreciated.
VIEW (AJAX):-
$('.lname').on("select2-selecting", function(e) {
$.ajax({
url: '<?php echo base_url('index.php/agent/customer/customersByLastname'); ?>',
data: {q:e.val},
success: function(data){
var obj = $.parseJSON(data);
if(obj.length>1) {
var items = [];
$.each(obj, function (key, val) {
items.push("<li onclick='showSearch("+val.customer_id+")' value='"+val.customer_id+"'>"+val.name+" "+val.lname+"</li>");
});
$("#lnm").html(items);
$('#listmodal').modal('show');
}
}
});
});
function showSearch(id_cust) {
$.ajax({
url: '<?php echo base_url('index.php/agent/customer/getCustomer'); ?>',
type:'POST',
data: {cid:id_cust},
success: function(data){
var obj = $.parseJSON(data);
$('#customer_id').val(obj[0].customer_id);
$('#select2-chosen-1').text(obj[0].customer_id);
$('#select2-chosen-2').text(obj[0].name);
$('#select2-chosen-5').text(obj[0].phone);
$('#select2-chosen-4').text(obj[0].zip_code);
$('#listmodal').modal('hide');
}
});
}
CONTROLLER FUNCTIONS:-
public function customersByLastname ()
{
$customers = $this->customer_m->getCustomerByLastname();
echo json_encode($customers);
}
public function getCustomer ()
{
$customer_id = $this->input->post('cid');
$this->load->model('customer_m');
$customer = $this->customer_m->getCustomerById($customer_id);
echo json_encode($customer);
}
MODEL:-
public function getCustomerByLastname(){
$search_term = $this->input->get('q');
$this->db->like('lname', $search_term);
$this->db->select('customer_id');
$this->db->select('name');
$this->db->select('lname');
return $keywords = $this->customer_m->get();
}
public function getCustomerById($customer_id){
$query = $this->db->query("SELECT * FROM naturescrm_customers WHERE id='".$customer_id."'");
return $query->result();
}
That is pretty much the code that I have done for this. If anything else is required. Kindly let me know. Thanks
i am using zf2. i want to load my second drop down by using the ajax call. i have tried with following code. i can get hard coded values. but i dont know how to add database values to a array and load that values to the drop down using ajax.
Ajax in phtml :
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
//code to load data to the dropdown
},
error:function(){alert("Failure!!");}
});
});
});
</script>
Controller Action:
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$projectusers[] = $this->getRoleTable()->fetchRoles($projectid);
// eturn a Json object containing the data
$result = new JsonModel ( array (
'projectusers' => $projectusers
) );
return $result;
}
DB query :
public function fetchRoles($id) {
$resultSet = $this->tableGateway->select ( array (
'projectid' => $id
) );
return $resultSet;
}
your json object new JsonModel ( array (
'projectusers' => $projectusers
) json object become like this format Click here for Demo
var projectkey = [];
projectkey = projectname.split(" - ");
var projectname = { "textData" : "+projectkey[1]+" };
$.ajax({
type:"POST",
url : "url.action",
data : projectname,
success : function(data){
$.each(data.projectusers,function(key,value){
$('#divid').append("<option value="+key+">"+value+"</option>");
});
});
});
<select id="divid"></select>
This is what i did in my controller. finaly done with the coding.
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$i=0;
$text[0] = $data->id. "successfully processed";
$projectusers = $this->getRoleTable()->fetchRoles($projectid);
foreach ($projectusers as $projectusers) :
$users[$i][0] = $projectusers->username;
$users[$i][1] = $projectusers->id;
$i++;
// eturn a Json object containing the data
endforeach;
$result = new JsonModel ( array (
'users' => $users,'count'=>$i
) );
return $result;
}
and the ajax is like this
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
// alert(data.users[0][0]+" - " + data.users[0][1] );
var count= data.count;
alert(count);
$('#myDropDown').empty();
for(var i=0;i<count;i++){
$('#myDropDown').append($('<option></option>').attr('value', data.users[i][1]).text(data.users[i][0]));
}
},
error:function(){alert("Failure!!");}
});
});
});
</script>
used the same zf2 query to access the database. thanks for the help everyone :)