Get related model through javascript in yii2 - javascript

I'm getting a Row from a table through javascript and action in Productnames controller.
The fields I'm getting is productid, productname and bottletype. So far it's fine.
JS
<?php
$script = <<< JS
$('#catid').change(function(){
var catid = $(this).val();
$.get('index.php?r=production/productnames/get-for-production',{ catid : catid }, function(data){
alert(data.unitprice);
// var data = $.parseJSON(data);
// $('#productnames-bottletype').attr('value',data.bottletype)
});
});
JS;
$this->registerJs($script);
?>
Action in ProductnamesController
public function actionGetForProduction($catid)
{
$bottle = Productnames::findOne(['productnames_productname'=>$catid]);
//$bottle -> select(['productnames.productnames_productname','productnames.bottletype','bottlename.unitprice'])->from('Productnames')->leftJoin('bottlename','productnames.bottletype = bottlename.bottlename')->where(['productnames_productname'=>$catid])->limit(1);
echo Json::encode($bottle);
}
Now I want to get data from bottlename table which is related to Productname table as productname.bottletype = bottlename.bottlename.
Table bottlename has 3 fields:
id, bottlename, unitprice.
I'm getting productname, bottlename from above mentioned code. What I want is to get the unitprice along with the above data.
Below is a screenshot what I'm getting now:

You should have in Productnames model a 'bottlename' relation to 'bottlename' table (I call it bottlenameRelation to distinguish from bottlename field):
public function getBottlenameRelation() {
return $this->hasOne(Bottlename::className(), ['bottlename' => 'bottletype']);
}
Then in the action add bottlenameRelation reference:
public function actionGetForProduction($catid)
{
$bottle = Productnames::find()->with('bottlenameRelation')->where(['productnames_productname'=>$catid])->asArray()->one();
echo Json::encode($bottle);
}
The json in output will contain bottlename relation fields.
For sake of completeness, you could output json in this way, that also add correct HTTP header:
public function actionGetForProduction($catid)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$bottle = Productnames::find()->with('bottlenameRelation')->where(['productnames_productname'=>$catid])->asArray()->one();
return $bottle;
}

Related

How to set json data into a html table

i want to display these json data into a html table. i am trying to do many things but i cant figure out how can i do it. So anyone can please help me to fix it.
the json data set will appear in the console. but i cant set it to a table.
this is my model
public function displayRecords()
{
$this->db->select('A.*');
$this->db->from('rahu AS A');
$this->db->where('A.status',1);
return $this->db->get()->result_array();
}
this is my controller
public function allrecodes()
{
/*script allow*/
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed here.');
}
$response= array();
$response['result'] = $this->RahuModel->displayRecords();
echo json_encode($response);
}
this is my js
var get_rec = function(){
//alert("WWW");
$.ajax({
//request ajax
url : "../dashbord/allrecodes",
type : "post",
contentType: "application/json",
dataType : "json",
success: function(dataset) {
//var myobject = JSON.stringify(result);
//alert(myobject[0]);
console.log(dataset);
console.log(dataset.result[0]['id']);
},
error: function() { alert("Invalide!"); }
});
};
the json dataset will appear in console.
And also this get_rec() in js file will called top of the page.
$(document).ready(function() {
//alert("Hello, world!");
get_rec();});
can anyone please help me to fix it.. thank you !!
There is no "simple" way to do it. You will have to loop through the resultset and render the html.
function renderTable(data) {
var result = ['<table>'];
var header = false;
for (var index in data) {
var row = data[index];
if (!header) {
// Create header row.
header = Object.keys(row);
var res = ['<tr>'];
for (var r in header) {
res.push("<th>" + header[r] + "</th>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
// Add data row.
var res = ['<tr>'];
for (var r in header) {
res.push("<td>" + row[header[r]] + "</td>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
result.push('</table>');
return result.join("\n");
}
document.getElementById('output').innerHTML = renderTable(data);
Have a div tag with id output on your HTML
<div id="output"></div>

How to insert multiple values to database table using php?

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);

Why are not you passing the parameters?

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);
}

Populate Dropdown based on another Dropdown Using Ajax, jQuery and Codeigniter

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;
}

jQuery blur based checking and print result to a view in codeigniter

Possibly someone asked question like as my question. But, I can't find any solution.
ProfileEditor.php (controller)
method 1:
public function modify_personal_information() {
$this->data['userinfo'] = $this->personal_information_of_mine($userid);
$this->load->view('layouts/header', $this->data);
$this->load->view('profile/personalinformation', $this->data);
$this->load->view('layouts/footer', $this->data);
}
method 2:
public function check_url_if_exists() {
$newportalurl = $this->uri->segment(2);
$this->results = $this->profile_model->checknewportalurl($newportalurl);
if ($this->results == 1) {
$this->status['status'] = 1;
$this->status['msg'] = 'This name is available. Thanks.';
} else {
$this->status['status'] = 0;
$this->status['msg'] = 'This name is not available. See suggestions.';
}
$this->load->view('profile/layouts/availiability', $this->status);
//or echo json_encode($this->status);
}
profile/personalinformation.php (views)
a form with <div id="urlsuggestions"></div>
profile/layouts/availiability.php (views)
where i am printing the message which i am getting from the check_url() function
ajax.js (ajax)
$('#newportalurl').blur(function() {
var fval = $(this).val();
var ifexists = fval.toLowerCase().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
$.ajax(baseurl + "check/"+ifexists, function(data) {
//i tried following things
//alert(window.location);
//$('#msgbox').html(data.msg).show().addClass('alert-success').delay(2000).fadeOut();
//$('#urlsuggestions').load(window.location + 'modifypersonalinformation #urlsuggestions');
});
});
Now, I am trying to load the message to personalinformation view. What I am doing wrong or what will be the procedure to do it? I actually want to know the process how codeigniter handle them.
Please try like this, im not able to get response from your metod.
$.ajax({
url: "<?= base_url("check/") ?>"+ifexists,
success: function (data) {
$("#urlsuggestions").html(data);// if you want to replace the data in div, use .html()
or if you want to append the data user .append()
}
});

Categories

Resources