This is what I've got so far:
This function that returns data from the model:
function get_user2()
{
$this->load->model('my_model');
$id=$this->input->post('users1');
$users2=$this->my_model->get_relations($id);
return $users2;
}
the model function:
function get_relations($usr)
{
$this->db->where('id',$usr);
$rel=$this->db->get('relacion');
if($rel->num_rows!=0)
{
$relacion=array();
foreach ($rel->result_array() as $row)
{
$relacion[]=array(
'id'=>$row['id'],
'username1'=>$row['username1'],
'username2'=>$row['username2'],
);
}
return $relacion;
}else{
return false;
}
}
and in my view:
<select name="users1" id="drop1">
<?php
if($opciones!=false){
foreach ($opciones as $row) {
echo '<option value="'.$row['user_id'].'">'.$row['username'].'</option>';
}
}
?>
</select>
<script src="jquery.js"></script>
<script type="text/javascript">
$("#drop1").change(function(){
$.ajax({
type: "POST",
url: "example.com/CI/index.php/evaluation/get_user2",
data: "users1="+$('#drop1').val(),
success: function(){
alert('it works!');
}
});
});
</script>
I want to fill a second dropdown with the options returned by the controller function, but the ajax request doesn't do anything so I haven't even got to that part. Can someone help me spot what's wrong? I already tested the controller and model's function and they work. And could you tell me how to fill the second dropdown's options?
Thank you very much!
Well I've a very similar code in one project to get some cities depending on the island the user choose. So wen the select changes, load the cities and enables the second select. The main difference is the way you pass the data.
<script type="text/javascript">
$("#idisla").change(function(){
if($("#idisla").val()!=""){
var dato=$("#idisla").val();
$.ajax({
type:"POST",
dataType:"html",
url:base_url+"admin/centros/municipios_select",
data:"idislajs="+dato,
success:function(msg){
$("#idmunicipio").empty().removeAttr("disabled").append(msg);
callback();
}
});
}else{
$("#idmunicipio").empty().attr("disabled","disabled");
}
});
</script>
The function only looks cities from the selected islad (id)
function municipios_select()
{
//el idIsla viene dado por el value del combo islas
$isla = $this->input->post('idislajs');
$data['municipios'] = $this->municipios_model->obtenMunicipios($isla);
echo $this->load->view("site/municipios_select",$data, TRUE);
}
Related
I tried to coding it. I am still getting stuck over it. The main goal was if user select value from mysqli database selected it and send the values to other pages. I know people recommend it use by AJAX. I tried to use it. still not working. I'll put details code below.
Main pages Code(main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
click
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
as alert box i am getting value of it but second pages get error that key value doesn't exist. here the second one pages (database1.php) -
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
so what the problem occurred?
UPDATED ANSWER
Thanks to #swati which she mentioned that use form tag instead of AJAX (i know its simple answer) still by the way thanks for answer. :)
UPDATED CODE FULL -
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
SECOND PAGE(database1.php) CHANGES LITTLE -
$database=$_GET['tables'];
You are calling each loop on page load that will give you the already selected value not the value which is selected by user.Also , this loop is not need as you have to pass only one value .
Your script should look like below :
<script type="text/javascript">
$(document).ready(function() {
//no need to add loop here
var search = '';
$("a").click(function() {
search = $("#tables option:selected").val(); //getting selected value of select-box
$.ajax({
method: 'post',
url: 'database1.php',
data: {
key: search
},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
Also , as you are using ajax no need to give href="database1.php" to a tag because you are calling this page using ajax .i.e: Your a tag should be like below :
<a>click</a>
And whatever you will echo in php side will be return as response to your ajax .So , your alert inside success function will show you that value.
I am using Codeigniter 3.1.1. I want City option to display base on the value selected with State option. Actually the City select option does not populate automatically when State option is selected. I tried to link the latest jQuery but still, it doesn't work. Your help is highly appreciated.
MyController.php
class HomeController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function index() {
$states = $this->db->get("demo_state")->result();
$this->load->view('myform_view', array('states' => $states ));
}
public function myformAjax($stateID) {
$result = $this->db->where("state_id",$stateID)->get("demo_cities")->result();
echo json_encode($result);} }
View:
<select name="state" id="state" class="form-control" style="width:350px">
<option value="">---Select State---</option>
<?php foreach($states as $key => $value)
{
echo "<option value='".$value->id."'>".$value->name."</option>";
} ?>
</select>
<select name="city" id="city" class="form-control" style="width:350px"></select>
Ajax:
$(document).ready(function() {
$('select[name="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/MyController/myformAjax/'+stateID,
type: "POST",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
});
You've not specified what problem you face when you run your code or what is the output or what is the error, so, we've no way of knowing what the real issue is. However, I'm sharing a working code (an excerpt from my project) of what you want; I've also changed the values according to your needs.
This follows a different approach as AJAX expects HTML to be
returned and that HTML is formed in PHP controller rather than on success in jQuery and then simply added to the desired id.
AJAX
$(document).ready(function() {
$('#state').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/MyController/myformAjax/'+stateID, // your-controller-path
// sometimes relative path might not work try with base_url() instead or configure your .htaccess properly
type: "POST",
dataType: "html", // expecting html
success:function(data) {
$('#city').empty();
$('#city').html(data); // change innerHTML of id='city'
}
});
}else{
$('#city').empty(); // $('#city').html('');
}
});
});
Controller
public function myformAjax($stateID) {
$cities = $this->db->where("state_id",$stateID)->get("demo_cities")->result(); // get all the cities -- probably want to do this in model
$cityOpt = '<option value="">--Select City--</option>'; // first option -- to prevent first option from automatically selecting when submitting data
foreach($cities as $city)
{
$cityOpt .= '<option value="'.$city->id.'">'.$city->city_name.'</option>'; // concatenate the next value
}
echo $cityOpt;
}
See if it helps you.
I want to populate textbox values automatically from DB based on dropdown selection.....I have tried this, but after selecting dropdown the page is refreshing but the values are not populated onto textbox....need Help!!
Table
Controller:
public function isrexpense()
{
$data['query'] = $this->Isr_model->getstates();
$data['names'] = $this->Isr_model->getAllNames();
$data['query1'] = $this->Isr_model->test();
$this->load->view("header");
$this->load->view('Isr/isrexpense', $data);
$this->load->view("footer");
}
Model:
function test()
{
$this->db->select('da_hq');
$this->db->from('isr_policy_master');
$this->db->where('state', $this->input->post('state'));
$query = $this->db->get();
return $query->result();
}
View:
<select class="js-example-basic-single form-control">
<?php
foreach($names as $row)
{
echo '<option></option>';
echo '<option value="'.$row->name.'">'.$row->name.'</option>';
}
?>
</select>
<select class="state form-control" id="state" name="state">
<?php
foreach($query as $row)
{
echo '<option value="'.$row->state_code.'">'.$row->state_name.'</option>';
} ?>
</select>
<script>
$('#state').on('change', function(){
var mainselection = this.value; // get the selection value
$.ajax({
type: "POST", // method of sending data
url: "<?php echo site_url(); ?>/Isr/isrexpense",
data:'selection='+mainselection,
success: function(result)
{
$("#hqda").html(result);
}
});
});
</script>
<input id="hqda" name="hqda" class="form-control" required type="number">
Controller :
public function isrexpense()
{
$data['query'] = $this->Isr_model->getstates();
$data['names'] = $this->Isr_model->getAllNames();
$this->load->view("header");
$this->load->view('Isr/isrexpense', $data);
$this->load->view("footer");
}
public function getValFromDb()
{
$state = $this->input->post('selection');
$query1 = $this->Isr_model->test($state);
echo json_encode(array('data'=>$query1));
}
Model:
function test($state)
{
$this->db->select('da_hq');
$this->db->from('isr_policy_master');
$this->db->where('state', $state);
$query = $this->db->get();
$result = $query->result();
if(count($result)>0)
{
return $result[0]['da_hq'];
}
else
{
return '';
}
}
View :
<script>
$('#state').on('change', function(){
var mainselection = this.value; // get the selection value
$.ajax({
type: "POST", // method of sending data
url: "<?php echo site_url(); ?>/Isr/getValFromDb",
data:'selection='+mainselection,
success: function(result)
{
console.log(result); // check this in your console and if require than use JSON.parse to get value
$("#hqda").val(result.data);
}
});
});
</script>
Textboxes don't have an "innerHTML" property. If you want to set the content of a textbox, you should set its value property. In jQuery you do this using the .val() method.
Replace
$("#hqda").html(result);
with
$("#hqda").val(result);
Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
and http://api.jquery.com/val/
P.S. You may also want to take a look at what your AJAX call returns - it's not clear whether it would return the content you're looking for or not - it appears to return a whole HTML view, rather than just a single value to place into a textbox.
Unable to get value from database in codeigniter. I tried to fetch data based on select box value(menu_code) without refreshing page using ajax but I got result undefined.
This my controller's code : login.php
public function get_menu_rights()
{
if (isset($_POST['name']))
{
$root_id = $this->input->post('menu_root_id');
$data['res'] = $this->login_model->get_menu_check($root_id);
// print_r($data['res']);
echo json_encode($data);
//$this->load->view('pages/role_rights',$data);
}
}
Below is my model code login_model.php
public function get_menu_check($root_id)
{
$this->db->select('menu_code,menu_name');
$this->db->from('create_menu as C1');
$this->db->where('C1.menu_root_id',$root_id);
$this->db->order_by('menu_code');
return $this->db->get()->result_array();
}
This is my view code role_rights.php
<form action="<?php echo base_url('login/get_menu_rights');?>" method="post">
<?php
print"<select class=\"form-control\" name=\"menu_root_id\" onchange=\"javascript:__doPostBack();\" id=\"menu_root_id\">"; ?> <option value="select">select</option>
<?php foreach($result as $res) { ?>
<option value="<?php echo $res->menu_code; ?>">
<?php echo $res->menu_name.'-'.$res->menu_code; ?>
</option>
<?php } ?>
</select>
</form>
</div>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
function __doPostBack()
{
var name = document.getElementById('menu_root_id').value;
var dataString='name='+ name;
$.ajax({
type:"post",
url:"<?php echo base_url('login/get_menu_rights'); ?>",
data:dataString,
cache:false,
dataType: 'json',
success: function(data)
{
var id = data[0];
var vname = data[1];
$('#output').html("<b>menu_code: </b>"+id+"<b> menu_name: </b>"+vname);
}
});
return false;
}
</script>
</div>
<div id="output"></div>
Hope this will help you :
Replace
$root_id = $this->input->post('menu_root_id');
with
$root_id = $this->input->post('name');
Your controller's get_menu_rights method should be like this :
public function get_menu_rights()
{
$root_id = $this->input->post('name');
if(! empty($root_id))
{
$data = $this->login_model->get_menu_check($root_id);
// print_r($data);
echo json_encode($data);
exit;
}
}
Your ajax success function should be like this :
success: function(data)
{
var html = '';
$.each(data,function(k,v){
alert(v);
html += "<b>menu_code: </b>"+v.menu_code+"<b> menu_name: </b>"+v.menu_name
});
$('#output').html(html);
}
There are a few things I noticed
$data is an undefined array & you are settings the result array returned by the model function to it's 'res' key
dataString is not a json neither it's a js array that you are sending
since you used json_encode, you need to use JSON.parse(data) in the ajax success
if you do have the result in $data['res'], then you need to do something like this - data=JSON.parse(data)['res']; now you can get id from data[0]
I think the query return empty please try this Code.....
public function get_menu_check($root_id)
{
$data = $this->db->select('C1.menu_code,C1.menu_name')
->from('create_menu as C1')
->where('C1.menu_root_id',$root_id)
->order_by('C1.menu_code')
->get();
if($data->num_rows() >= 0)
return $data->result_array();
else
return false;
}
Hope your are fine!
I'm would like to execute a request (SQL) like this one:
SELECT Name FROM course WHERE IdSectionFK = '.$idSectionFK.';
I have the list of sections:
while($row = $selectAllSection->fetch(PDO::FETCH_OBJ)){
echo "<option value=".$row->IdSection.">".$row->Name."</option>";
}
And I would like to display the data only for the selected value. I tried something like this to get the value of the list:
<script>
function displayVals() {
var idSection = $("#sectionListe").val();
$.post('index.php', { 'idSection': idSection },function (){
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
}
$("select").change(displayVals);
displayVals();
</script>
So, the variable "idSection" is equale to the PHP variable "idSectionFK" in my SQL request.
But how can I execute the right SQL request ?
Thank you so much for your help!
Lapinou.
AJAX is the solution.
JS code:
function displayVals() {
var idSection= $("#sectionListe").val();
$("p").html(idSection);
$.post('/url/to/php/file', { 'idSection': idSection }, function (response) {
// do something with the response here
// e.g: $('select').append(response);
console.log(response);
});
}
$("select").change(displayVals);
displayVals();
PHP code to process the received data:
$idSectionFK = 0;
if (isset($_POST['idSection'])) {
// get the ID from ajax, run SQL here
$idSectionFK = intval($_POST['idSection']);
$query = "SELECT Name FROM course WHERE IdSectionFK = '.$idSectionFK.';";
// .... your code ...
}
Just to give you the basic idea.