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;
}
Related
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);
}
I have to call this php file
<?php
session_start();
require 'connect.php';
//Prendo le tre variabili dalla form
if(isset($_POST['Titolo'])) {
$title_rew = $conn->real_escape_string($_POST['Titolo']);
}
if(isset($_POST['Voto'])) {
$voto_rew = $conn->real_escape_string($_POST['Voto']);
}
if(isset($_POST['Review'])) {
$review_rew = $conn->real_escape_string($_POST['Review']);
}
if(isset($_POST['ID_locale'])) {
$id_rew = $conn->real_escape_string($_POST['ID_locale']);
}
$current_date = date('Y-m-d');
$sql = "INSERT INTO recensione (Titolo_R, Voto_R, Commento_R, IDnegozio_R, Email_R, Utente_R, Data_R)
VALUES ('$title_rew', '$voto_rew', '$review_rew','$id_rew','".$_SESSION['emailSessione']."','".$_SESSION['usernameSessione']."','$current_date')";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//Chiudo la connessione
$conn->close();
header("location:..\locals_page.php");
?>
I've tried with this
$("#submit_review").unbind().click(function() {
var chx = document.getElementsByName("Voto");
for (var i=0; i<chx.length; i++) {
// If you have more than one radio group, also check the name attribute
// for the one you want as in && chx[i].name == 'choose'
// Return true from the function on first match of a checked item
$.post("php/insert_comment.php" );
return true;
}
// End of the loop, return false
alert("Seleziona almeno il voto!");
return false;
});
But there it's not working. It's strange because with a button submit and a
<form role="form" id="review-form" method="post" action="php/insert_comment.php">
It was working.
But now I have to do this without a button type "Submit"
Thank you to all in advance
just try this
$.ajax({
url : "php/insert_comment.php",
type : "post",
data : $("#review-form").serialize();
success : function(data){
alert(data); // show when ajax return response from php script
}
})
for that registered onclick event on that button and send ajax request using jquery
$.ajax({
type:'POST',
url : "your url",
data : $('form').serializeArray(),
cache: false,
success:function(response){
console.log(response) // your result from php
}
})
Single quotes treat $ as a string
$sql = "INSERT INTO recensione (Titolo_R, Voto_R, Commento_R, IDnegozio_R, Email_R, Utente_R, Data_R)
VALUES ('".$title_rew."', '".$voto_rew."', '".$review_rew."','".$id_rew."','".$_SESSION['emailSessione']."','".$_SESSION['usernameSessione']."','$current_date')";
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'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;
}
I am using Jquery Autocomplete to fetch a list of tags from a mysql table. When the user picks one tag from the list, it gets saved on the page. I am trying to prevent the already saved tag from being displayed again.
Here is my code:
HTML
<input type="text" id="tag">
<input type="text" id="tags" style="display:none;">
Jquery
$('#tag').autocomplete({
source : function(request, response) {
$.ajax({
url : 'tags.php',
dataType : "json",
method : 'post',
data : {
searchQuery : request.term,
selectedTags: $('#tags').val() //sends already selected terms
},
success : function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label : code[0],
value : code[0],
data : item
}
}));
},
error: function(jqxhr, status, error)
{
alert(error);
}
});
},
autoFocus : true,
minLength : 1,
select : function(event, ui) {
var names = ui.item.data.split("|");
tag_ids = [];
tag_names = [];
tags = $('#tags').val();
if(tags != '')tag_names = tags.split(',');
tag_ids.push(names[1]);
tag_names.push("'" + names[0] + "'");
$('#tags').show();
$('#tags').val( tag_names.join( "," ) );
$('#tag').val('');
}
PHP
$searchQuery = $_POST['searchQuery'];
$selectedTags = $_POST['selectedTags'];
if(!empty($selectedTags))
{ $query = $db->prepare("SELECT * FROM tags WHERE name LIKE ? AND name NOT IN ?");
$query->execute(array($searchQuery . "%", $selectedTags));
}
else
{
$query = $db->prepare("SELECT * FROM tags WHERE name LIKE ?");
$query->execute(array($searchQuery . "%"));
}
When I select the first suggestion, it gets saved in #tags but then no other suggestion is displayed. If there is any other suggestion to achieving this, that'd be great.
I figured it out. I was trying to pass an array to the prepared statement.
PDO doesn't work that way.
To solve this, I declared the number of parameters first and then put them in the prepared statement while using foreach to bindvalue to each parameter.
Here is the final solution:
//exploding the string to an array first
$selectedTags = explode(',', $selectedTags);
//creating another array with parameters equal to the size of the selectedTags
$bindValues = implode(',', array_fill(0, count($selectedTags), '?'));
//putting the parametes
$query = $db->prepare("SELECT * FROM tags WHERE name LIKE ? AND name NOT IN (" . $bindValues .")");
//binding values
$query->bindValue(1, $searchQuery . '%');
//Now, using foreach to bind selected tags values
foreach($selectedTags as $k => $selectedTag)
{
//using k+2 as index because index starts at 0 and first parameter is the search query
$query->bindValue($k+2, $selectedTag);
}
$query->execute();
And this solved the problem. I hope it helps others too.