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);
}
Related
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);
},
})
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
Here is my little script code I want to get data from codeingiter controller. I get json data from controller to view ajax, but It print with html page code.
any one can help me here, How can I solve this.
I only want to get json data ans a variable data to my page.
this is output that I am getting but this is comming with html code and I don't want html code.
[{"id":"1","p_name":"t_t11","p_type":"t_t1","paid_type":"0"},{"id":"2","p_name":"t_t12","p_type":"t_t1","paid_type":"1"},{"id":"3","p_name":"t_t1","p_type":"t_t1","paid_type":"0"}]
I have follow some question answers but can't et success, because that question's answers not related to me.
Link 1
Link 2 and many more...
<script>
$("a.tablinks").on('click',function(e){
e.preventDefault();
var p_name = $(this).attr('value');
alert(p_name);
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'text',
type: "POST",
data:{p_name : p_name},
success : function(data){
alert(data);
if(data !=""){
var obj = JSON.parse(data);
alert(obj.id);
/*$.each(obj, function(key,val){
console.log(key);
console.log(val); //depending on your data, you might call val.url or whatever you may have
});*/
}else{
alert(data+ '1');
}
},
error : function(data){
//var da = JSON.parse(data);
alert(data+ '2');
//alert(da+ '2 da ');
}
});
});
</script>
Here is controller code.
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
echo json_encode($query['res']);
$this->load->view('teq', $tabs_data);
}
You added view at the end of your function that return view's code.
Remove line:
$this->load->view('teq', $tabs_data);
You can either use
if ($this->input->is_ajax_request()) {
echo json_encode($data_set);
}else{
//Procced with your load view
}
Or if you're avoiding ajax request check then please pass any extra paramter from your ajax call then then check for its existence at your controller and on behalf of it proceed your conditional statement . it will solve your problem
Change your controller method like this:
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
// if ajax request
if ($this->input->is_ajax_request()) {
echo json_encode($query['res']);
return; // exit function
}
$this->load->view('teq', $tabs_data);
}
In your ajax code chage dataType: to json
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'json',
type: "POST",
data:{p_name : p_name},
success : function(res)
{
if(res !=""){
alert(res.id);
}else{
alert(res+ '1');
}
}
});
And in your controller
public function gettabdata()
{
if($this->input->post('p_name'))
{
$p_name = $this->input->post('p_name');
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
if($query['res'])
{
$resp = $query['res'];
}
else
{
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
}
else
{
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
$this->load->view('teq', $tabs_data);
}
}
Hope this helps :)
I just wanna ask how to populate a dropdown based on another dropdown's value.
When I select a Campaign, it will show the names of the people that are in that Campaign in another dropdown but the value must be the id of the name.
Here is my Model
function get_agents($campaign_id)
{
$campaign_id1 = mysqli_real_escape_string($this->db->conn_id,trim($campaign_id));
$query = $this->db->query("SELECT tbl_employee.emp_id, CONCAT(tbl_applicant.fname, ' ', tbl_applicant.lname) AS fullname FROM tbl_applicant INNER JOIN tbl_employee ON tbl_employee.apid=tbl_applicant.apid INNER JOIN tbl_account ON tbl_employee.acc_id=tbl_account.acc_id WHERE tbl_account.acc_id='".$campaign_id1."'");
return $query->result();
}
Here is my Controller
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$this->KudosModel->get_agents($campaign_id);
echo $result;
}
Here is my AJAX
$('#addCampaign').on('change', function(){
$.ajax({
type : 'POST',
data : 'campaign_id='+ $('#addCampaign').val(),
url : 'controller/method',
success : function(data){
$('#anyname').val(data);
}
});
}); //I dont know what to do here
Thanks in advance guys!
I think you need some manipulation in controller like-
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$employees = $this->KudosModel->get_agents($campaign_id);
/*
foreach($employees as $employee)
{
echo "<option value='".$employee->emp_id."'>".$employee->fullname."</option>"
}*/
// for json
$employeesList = [];
foreach($employees as $employee)
{
array_push($employeeList,array('emp_id'=>$employee->emp_id,'fullnme'=>$employee->fullname));
}
echo json_encode($employeeList, JSON_FORCE_OBJECT);
}
now in ajax success function-
success : function(data){
// anyname should be the id of the dropdown
// $('#anyname').append(data);
// for json
$json = JSON.parse(data);
// empty your dropdown
$('#dropdownId').empty();
$.each($json,function(key,value){
$('#dropdownId').append('<option value="'+key+'">'+value+'</option>');
})
}
You can simply iterate through your data and add options to your second Select
$('#addCampaign').on('change', function(){
$.ajax({
type : 'POST',
data : 'campaign_id='+ $('#addCampaign').val(),
url : 'controller/method',
success : function(data){
//data returns your name, iterate through it and add the name to another select
$.each(data, function($index, $value) {
$('#secondSelect').append($("<option></option>").val($value.id).html($value.name));
});
}
});
});
One thing, if you need a listener on your second <select> lets say on('click'), you need to add it back once you populated it. If not, Jquery won't recognize the new values.
Edit
Also, as #PersyJack stated, you need to asign the variable $result to something if you want to return it.
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$result = $this->KudosModel->get_agents($campaign_id);
echo $result;
}
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 :)