I have problem in ajax posting. i try to get category when select parent category in drop down.but data is post.
my business controller
public function getcat($id)
{
echo "sdfad";
$cr=new Categoryrepo();
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($cr->getcatbyparentid($id)));
}
my category model
public function getcatbyparentid($id)
{
$this->db->select('id,name');
$this->db->from('category');
$this->db->where('parent',$id);
return $query=$this->db->get();
}
my ajax code
$(document).ready(function(){
$("#parent").change(function(){
var id=$('#parent').val();
alert(id);
$.ajax({
type:"POST",
url:"<?php echo base_url()?>business/getcat/"+id,
success: function(data)
{
alert(data);
}
});
});
});
please help me how to solve it
now it working ......
Json return proper data like [{"id":"8","name":"mobile"},{"id":"10","name":"mno`"}].
now Questions is how to bind this data in drop down list..
Try this:
Model:
public function getcatbyparentid($id){
$this->db->select('id,name');
$this->db->from('category');
$this->db->where('parent',$id);
// just return query! In controller we will handle it.
return $query;
}
Controller:
$this->load->model("Categoryrepo");
$html = $this->Categoryrepo->getcatbyparentid($id);
$content = "<select name='yourName'>";
foreach($html->result() as $row){
$content .= '<option value="'. $row->column_name1 .'">' . $row->column_name2 . "</option>";
}
$content .= "</select>";
$result = array('status' => 'ok', 'content' => $content);
echo json_encode($result);
Modify your model function as below:
public function getcatbyparentid($id)
{
$this->db->select('id,name');
$this->db->where('parent',$id);
$query=$this->db->get('category');
if($query->num_rows() == 0)
{
return FALSE;
}
else
{
return $query->result() // or return $query->row() <if you want only one value to be return>
}
}
Related
I'm not able to filter table data using Ajax. When I select BANK CREDIT from drop down it should fetch employee details with modeofpay(table column) as "BANK CREDIT" and when I select NEFT it should display employee details with modeofpay(table column) as "NEFT". As of Now nothing happens when i select drop down.
Controller:
public function filter($key = '')
{
$this->load->helper('url');
if ( $key == 'BANK CREDIT' ) {
$this->load->model('JcMeetingExpense_model');
$data = $this->JcMeetingExpense_model->getCredit($key);
}
else
{
$this->load->model('JcMeetingExpense_model');
$data = $this->JcMeetingExpense_model->getNeft($key);
}
echo json_encode($data);
}
Model:
public function getCredit($key)
{
$sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
public function getNeft($key)
{
$sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
View:
<script type="text/javascript">
var paymode = $("#mode").change(function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("JcMeetingExpense/filter/key/") ?
>'+paymode,
data:"key="+paymode,
dataType:'json',
success:function(data){
$("#viewjcexpense").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
<select name="mode" id="mode" >
<option value="BANK CREDIT">CREDIT</option>
<option value="NEFT">NEFT</option>
</select>
is your onchange event working ?
let's check with
$("#mode").change(function(){
alert(1);
});
if when u selected an option would be show the alert that's mean ur event working ,
now if that's working fine let's try to playing with ajax and do little recode, here i used post method
[ VIEW ]
$("#mode").change(function(){
$.ajax({
type : 'POST',
url : '<?=base_url(); ?>JcMeetingExpense/filter/',
data : { key : $("#mode").val() },
success : function(data){
console.log(data);//let's check on console what's response is
}
});
})
[CONTROLLER]
public function filter()
{
$this->load->helper('url');
$this->load->model('JcMeetingExpense_model');
$dataKey = $this->JcMeetingExpense_model->get_data_by_key();
echo json_encode($datadataKey);
}
[MODEL]
public function get_data_by_key()
{
//do post here let's say
$key = $this->input->post("key");
// i looked your query is vulnerable to SQL Injection
/* $sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array(); */
//so let's use query builder
$this->db->select("*");
$this->db->from("employee");
$this->db->where("modeofpay",$key);
$q = $this->db->get();
return $q->result_array();
}
now check response in console
<script type="text/javascript">
$("body").on('change','#mode',function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("JcMeetingExpense/filter/key/") ?
>'+paymode,
data:"key="+paymode,
dataType:'json',
success:function(data){
$("#viewjcexpense").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
try this script instead of your previous script
i have changed $("#mode").change(function(){}); with $("body").on('change','#mode',function(){});
now guys i know this is a simple error but no matter what i try i cant access the json values whenever i use alert after parse json it shows me undefined
why is it caused ?
here is my code
script
function getfriend_requests()
{
var id=$('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/getallfriends"); ?>',
data:{id:id},
dataType:'json',
success:function(data)
{
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
alert(json);
$.each(json,function(key,data)
{
alert(data.object);
});
}
});
}
now the controller
public function getallfriends()
{
$id=$this->input->post('id');
$this->load->model('Pmodel');
$data['senders']=$this->Pmodel->get_all_user_friends_sender($id);
$data['recievers']=$this->Pmodel->get_all_user_friends_reciever($id);
echo json_encode($data);
}
now the model
public function get_all_user_friends_sender($id)
{
$this->db->select('*');
$this->db->from('user_friend');
$this->db->join('user_data', 'user_friend.senders_id = user_data.id');
$this->db->join('user', 'user_friend.senders_id = user.id');
$this->db->where('user_friend.senders_id',$id);
$query = $this->db->get();
$row = $query->result_array();
// print_r($row);
return($row);
}
public function get_all_user_friends_reciever($id)
{
$this->db->select('*');
$this->db->from('user_friend');
$this->db->join('user_data', 'user_friend.recievers_id = user_data.id');
$this->db->join('user', 'user_friend.recievers_id = user.id');
$this->db->where('user_friend.recievers_id',$id);
$query = $this->db->get();
$row = $query->result_array();
// print_r($row);
return($row);
}
now when i try to return the value with result_array iy shows me undefined value but if i use $row_array it return only single value from each model.
can you tell me where i am going wrong?
You have array of objects in json response so in success function try like this..
$.each(json,function(key,data)
{
alert(data.key);//where key is key of pointing object
});
In your controller try to change
echo json_encode($data);
to
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
I have an issue when using AJAX to filter data on the table. I have a select box and table on the page. I want to filter data on the table using the select box. example, if the user chooses value 'Ganjil' on the select box then table just show row that has data 'Ganjil'.
AJAX Script:
<script>
var semester = $("#inputJenis").change(function(){
$.ajax({
type:"POST",
url:'<?php echo base_url("search/filter") ?>',
data:"key="+semester,
dataType:'json',
success:function(data){
$("#tableData").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
Controller:
public function filter()
{
$this->load->helper('url');
$key = $this->input->post('semester');
if ( $key == 'Ganjil' ) {
$this->load->model('filter_model');
$data = $this->filter_model->getGanjil($key);
} else {
$this->load->model('filter_model');
$data = $this->filter_model->getGenap($key);
}
echo json_encode($data);
}
Model:
public function getGanjil($key)
{
$sql = "SELECT * FROM tahunajaran WHERE jenis = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
public function getGenap($key)
{
$sql = "SELECT * FROM tahunajaran WHERE jenis = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
When I choose the value of select box table show nothing.
1st Solution : use $key = $this->input->post('key'); in controller as you access key value pair. So in AJAX call $key is Key. You cant access javascript variable semester like $this->input->post('semester'); in your code.
2nd Solution :
in ajax call url:'<?php echo base_url("search/filter/key/") ?>'+semester
Use $key='' as parameter in controller method .
public function filter($key='') as there is no $key accessible in your controller method. You should be accessing in your controller as a parameter. So you can use it in model . In your case there is no $key coming as a parameter in controller.
Also in your code use
$key = $this->input->post($key); as we access $key thru parameter.
-------------Update 1----------
As per your requirement , AJAX call
<script>
var semester = $("#inputJenis").change(function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("search/filter/key/") ?>'+semester,
data:"key="+semester,
dataType:'json',
success:function(data){
$("#tableData").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
And your controller should be like this ->
public function filter($key = '')
{
$this->load->helper('url');
if ( $key == 'Ganjil' ) {
$this->load->model('filter_model');
$data = $this->filter_model->getGanjil($key);
} else {
$this->load->model('filter_model');
$data = $this->filter_model->getGenap($key);
}
echo json_encode($data);
}
I'm using codeigniter, I had a problem to process a data using jQuery $.post function. I want to send a value such as subjectid to ajax_get_subject_credit function and retrieve another field within same database table. The result shows on another text field. Here is my code.
View:
$.post('<?php echo site_url('academic/ajax_get_subject_credit'); ?>', {'subjectid':subjectid}, function(data){
$('#chours' + id).val(data); });
This get a value from drop-down and I want to make a text field automatic populate from drop-down. #chours is a text field ID.
Controller:
function ajax_get_subject_credit($result)
{
$this->db->select('subjectid, subjectcredit');
$query = $this->db->get('ref_subject');
$result = $query->result_array();
$query->free_result();
$subjectid = array();
foreach($result as $row)
{
$result = $result + array($row['subjectid'] => $row['subjectcredit']);
}
return $result;
}
Modified In Controller
I also tried using this statement in controller for direct calling the field but still no success :
function ajax_get_subject_credit($subjectid)
{
$this->db->select('subjectid, subjectcredit');
$this->db->where('subjectid',$subjectid);
$query = $this->db->get('ref_subject');
$credithour = $query->row()->subjectcredit;
$query->free_result();
echo $credithour;
}
I am going to provide a general example here
in view file
$.post('<?php echo site_url("test/test"); ?>', {'id':1}, function(response){
if(response.success)
{
alert(response.message);
} else
{
alert('Something went wrong!!');
}
}, 'json');
in controller Test.php
function test()
{
$id = $this->input->post('id');
//do additional stuff
$result = 'i am coming right out of controller!! ';
echo json_encode(array('success' => true, 'message' => $result));
}
Dont use return to return value to AJAX. use echo
change this,
return $result;
to
echo $result;
If you want your method to return an array that the javascript can use to populate a dropdown, you probably don't want to return a string.
Try something like this:
function ajax_get_subject_credit()
{
$query = $this->db->select('subjectid, subjectcredit')->get('ref_subject');
$result = $query->result();
$out = array();
foreach($result as $row) {
$out[$row->subjectid] = $row->subject_credit;
}
header('Content-Type: application/json');
echo json_encode($out);
}
This will return a JSON array to your view, which your javascript method can use to populate the dropdown with values and labels.
Here is my Result:
In View :
function subjectid_change(id, subjectid){
//Set value
setValue(id, subjectid);
$.post('<?php echo site_url('academic/ajax_get_subject_credit'); ?>', {'subjectid':subjectid}, function(response){
if(response.success)
{
$('#chours' + id).val(response.value);
} else
{
alert('Something went wrong!!');
}
}, 'json'); }
And my controller :
function ajax_get_subject_credit()
{
//Get Post Value
$subjectid = $this->input->post('subjectid');
//Select subjectid,subjectcredit FROM
$this->db->select('subjectid, subjectcredit');
//Where subjectid = 'subjectid'
$this->db->where('subjectid',$subjectid);
//Database name
$query = $this->db->get('ref_subject');
$credithour = $query->row()->subjectcredit;
$query->free_result();
$result = $credithour;
echo json_encode(array('success' => true, 'value' => $result));
}
Thanks to everybody who helped me.
The script below works as far as i can tell:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#add').bind('keypress', function(e) {
if(e.keyCode == 13){
var add = $("#add").val();
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?php echo site_url("home/jsonAddData"); ?>",
data: add,
json: {title_posted: true},
success: function(data){
if(data.title_posted == true) { // true means data was successfully posted.
$("#success").append("Success").fadeIn(400);
} else if(data.title_posted == false) { // false means data failed to post.
$("#success").append('Failure').fadeIn(400);
}
}
});
}
});
});
</script>
The problem I'm experiencing with the code below is that the mysql insetion query just wont work. It creates the row in the table and auto-increments but for some odd reason it wont pass the 'var add' in the Javascript above to the Ci script below and perform an insertion in the db. Any thoughts or ideas?
<?php
class home extends CI_Controller {
function __construct() {
parent::__construct();
}
function index() {
$data = array();
$data['lists'] = $this->displayList();
$this->load->view('home', $data);
}
function displayList() {
$str = '';
$query = $this->db->query("SELECT * FROM data");
foreach ($query->result() as $row) {
$b = '<input name="completed" type="checkbox" />';
$a = $row->title . "<br>";
$str .= $b.$a;
}
return $str;
}
function jsonAddData() {
if($this->input->is_ajax_request()) {
$title = $this->input->post('title');
$query = $this->db->query("INSERT INTO data (title) VALUES ('$title')");
header('Content-type:application/json');
if($query) echo json_encode(array('title_posted' => true));
else echo json_encode(array('title_posted' => false));
}
}
}
?>
In
$.ajax({
...
data: {title: add}
Not just a string