my code :
model :
function get_all_transaksi_proses() {
$rs = $this->db->query("SELECT a.id_transaksi, ETC");
return $rs;
}
control :
public function ambilDataTransaksi() {
$data=$this->transaksi->get_all_transaksi_proses();
echo json_encode(array("result" => $data->result_array()));
}
view :
$.getJSON("<?php base_url();?>transaksiDigorCont/ambilDataTransaksi", function(data) {
alert("jhjh");
});
this my code but it cant show alert("jhjh"), so it can't in to function(data) ?
You should be doing like:
$.getJSON( "<?php echo base_url(); ?>controllername/somefunction", function( data ) {
//do something with data
});
and in your controller, create a function say, 'somefunction', and
//controller code
function somefunction() {
//load model if not already done in constructor
//get data from model
$data = $this->your_model->get_all_transaksi_proses();
echo json_encode($data);
}
See the $.getJSON documentation:
jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] )
It expects a URL as the first argument.
Related
To put in simple words I want status1 to go to ajaxleadsreport controller
A bit more complex explanation:
I have 2 view classes called indexreport and ajaxleadsreport. ajaxleadsreport fetches all the data and displays it. Now I have a GET variable that is being passed to indexreport which I want to be able to pass it to ajaxleadsreport to filter the current data according to the GET variable that has been passed.
Controller Class:
public function listsreport($slug='')
{
$status1 = $this->input->get('status');
print_r($status1);
$main['content']=$this->load->view('crm/leads/indexreport',$content,true);
}
public function ajaxleadsreport($p='')
{
$output = array( 'html'=>$this->load->view('crm/leads/ajaxleadsreport',$content, true));
echo json_encode($output);
}
indexreport View Class:
<?php
$i=$return=$uriseg;
$post=$this->input->post(); $sess=$this->session->userdata();
$post = $post?$post:$sess;
?>
<div>
...
</div>
$(document).ready(function (){
getleads();
});
function getleads(p){
$.ajax({
type: "post",dataType:"json",async:false,cache:true,
url: "<?php echo site_url('leads/ajaxleadsreport'); ?>"+( parseInt(p)>0?'/'+p:''),
data: $('#objlistform').serialize(),
success: function(e){$('#leadswrap').hide().html(e.html).fadeIn('slow');}
}); return false;
}
ajaxleadsreport View class:
<?php
$sess=$this->session->userdata();
$status1 = $this->input->get('status');
// This is where I'm trying to put my GET value of status for filtering but it gives NULL.
$post = array('fstatus'=> $status,'fpriority'=> $sessn['fpriority']);
$postd = json_encode(array_filter($post));
?>
...
<script>
$(document).ready(function() {
function sendreq(){
setpostdatas();cleartable();getleads();
}
var slug = '<?php echo $slug?>';
var postd = '<?php echo $postd; ?>';
$('#item-list').DataTable({
"processing": true,
"stateSave": true,
"serverSide": true,
"ordering": false,
"ajax": {
url: "<?php echo site_url(); ?>leads/loadLeads",
data: {slug: slug, postdata: postd},
type : 'POST',
"dataSrc": function ( d ) {
d.myKey = "myValue";
if(d.recordsTotal == 0 || d.data == null){
$("#item-list_info").text("No records found");
}
return d.data;
}
},
'columns': [
{"data": "id", "id": "id"},
{"data": "lead_status", "lead_status": "lead_status"},
{"data": "priority", "priority": "priority"},
]
});
As you can see in the code above, I've tried $status1 = $this->input->get('status'); in ajaxleadsreport View class but the output for that is NULL, since the GET value is passed in my indexreport view class. When I do a print_r($status1) in indexreport controller it gives the right output, but NULL in ajaxleadsreport controller.
So basically now I need a way to pass this GET value to ajaxleadsreport controller.
You can use flashdata here:
Set your status to flashdata then get it out in ajaxleadsreport like this: (flashdata only exist once on next request)
$this->session->set_flashdata('status', $status1);
In ajaxleadsreport:
$this->session->flashdata('status');
In the controller class declare the variable:
protected $status1;
public function listsReport() {
$this->status1 = $this->input->get('status');
// [...]
}
Then you can access $this->status1 from any function that is invoked after.
I am calling a PHP function from a JQuery ajax method. Below is how the response looks from ajax call:
My question is: how to iterate over this array in jquery to get the values?
I am getting "Cannot use 'in' operator to search for 'length' in Array" if I iterate using $.each.
Below is the Code:
$("#member_country").change(function() {
var country = $(this).val();
//alert(country);
var ajax_url_mtypes = ins_membership_ajax.ajax_url;
//alert(ajax_url_mtypes);
jQuery.ajax({
url:ajax_url_mtypes,
data:{country:country,
action: "ins_get_membershiptypes_from_country"},
method:'GET',
contentType: "application/json;charset=utf-8",
success:function(response) {
//var resp = $.trim(response);
alert(response);
$.each(response, function( key, value ) {
alert( key );
alert( value );
});
}
});
PHP Code:
public static function getMembershipTypesNonAdmin($country){
$rtn = array();
global $wpdb;
$table = $wpdb->prefix.self::TABLE_NAME;
$query = "SELECT * FROM {$table} where admin_only = 'false' order by member_type";
$results = $wpdb->get_results($query);
if($results){
foreach($results as $row){
$membership_type = INS_Membership_Types::loadById($row->id);
$membership_type->setDues(INS_Membership_Types::getDuesByEconomy($country, $membership_type->getMemberType()));
$rtn[] = $membership_type;
}
}
return $rtn;
}
private $dues;
public function getDues()
{
return $this->dues;
}
public function setDues($dues)
{
return $this->dues = $dues;
}
You can iterate over objects through for in loop. like as below:
for(var prop in object){
console.log(object[prop]);
}
Hope this helps.
Try with json.
Use
json_encode()
in the php code and
dataType: "json"
in the ajax call
I try to load database data in my Select2 input. (Im working on CI)
Here's my code from the controller : transforms array in echo json
class Ajax extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('client');
}
public function returnClientsAjax(){
echo json_encode($this->client->getClients());
}
}
Model : returning an array of results
function getClients(){
return $this->db->query("SELECT idclient AS id, CONCAT(societe,' [', nom,']') as text FROM du_client WHERE (societe != '' AND nom != '') AND evo2012 >=2 AND type_client != 'Particulier' AND statut_client = 'Demandeur' AND idclient = 6141;")->result_array();
}
My Select2 :
$("#sel_clients").select2({
placeholder: "Search for an Item",
ajax: {
dataType: "json",
url: "http://commexpert.dev.local/ajax/returnclientsajax",
results: function (data) {
return {results: data};
}
}
});
The input still empty so, don't know what to do.
Thnaks :D
I think something is missing on your data results method. Here is my code from working ajax select2 component:
results: function (data) {
var results = [];
var id1 = data.id;
var name = data.text;
$.each(data.data, function(index, item){
results.push({
id: item[id1],
text: item[name].trim()+' : '+ item[id1]
});
});
return {results: results};
}
also, I'm having somewhat diff data call also:
data: function (term) {
try {
mirko = $(this).closest('[rendered]').find( "input[fparamname$=" + $(this).attr('flookupfiltref') + "]" ).val();
if (mirko.indexOf(' : ') >=0 ) { // pocetna vrijednost
mirko = mirko.split(' : ')[1].trim();
}
} catch(e){
mirko = '';
}
return {
sp_name: $(this).attr('objectname'),
fl_name: $(this).attr('fparamname'),
node_id: $(this).attr('node_id'),
bound: mirko,
q: term,
};
},
I'm having somekind of manipulation before sending or returning q to server,, but I hope that can help you for your service :)
hth, k
I've struggeled alot with this .
I wanna send an ID in the CI model and get the returned value via CI controller
My view is
<script type="text/javascript">
function showsome(){
var rs = $("#s_t_item option:selected").val();
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
contentType: 'json',
data: {item_id: rs},
success: function(output_string){
//$('#result_area').val(output_string);
alert(output_string);
}
});
}
</script>
My Controller method is
public function get_unit_item()
{
$received = $this->input->post('item_id');
$query = $this->units_model->get_unit_item($received);
$output_string = '';
if(!is_null($query)) {
$output_string .= "{$query}";
} else {
$output_string = 'There are no unit found';
}
echo json_encode($output_string);
}
And my model function responsible
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() >0 ){
$j = $result->row();
return $j->unit_item_info ;
}
}
Html codes
<?php $id = 'id="s_t_product" onChange="showsome();"';
echo form_dropdown('product_id[]', $products, $prod,$id); ?>
I tried to use the id only but failed to fire so passing a function onchange seems to pick the item and fire
Using firebug I can see that the post request sends item_id=2 but the response length is 0 and with php result code 302
POST
RESPONSE
How can I achive this?(The model is loaded on the contructor)
Do slighly change your controller and model:
// Model
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() > 0 ) {
$j = $result->row();
return $j->unit_item_info ;
}
else return false;
}
// Controller
public function get_unit_item()
{
$received = $this->input->post('item_id');
$return = array('status'=>false);
if( $query = $this->units_model->get_unit_item($received) ) {
$return['status'] = true;
// Add more data to $return array if you want to send to ajax
}
$this->output->set_content_type("application/json")
->set_output(json_encode($return));
}
Check returned values in JavaScript:
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
dataType: 'json',
data: {item_id: rs},
success: function( response ){
if( response.status === true ) {
alert('Everything Working Fine!');
console.log( response );
}
else alert('Something went wrong in query!');
}
});
After trying various approaches I have finally found what really is the problem and i think this might be the problem for all with the 302 found error. In this project (server) there're two systems within the same root and each has got its own codeigniter files. As seen above i was using
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
url : base_url+ '/' + controller+ '/get_unit_item',
as the value for url but i tried to put the full url from the base and it worked so now it is
url: '<?php echo base_url(); ?>index.php/en/items/get_unit_item',
. I think for any one with the redirect issue the first thing to check is this
I am using codeigniter to develop my app. And I am using jquery to send some json data.
This is my code :
Model :
public function updateRequest($id_request, $jenis_request, $keluhan ){
$data= array(
'jenis_request' => $jenis_request,
'keluhan' => $keluhan
);
$this->db->where('id_request', $id_request);
$query = $this->db->update('tbl_requestfix', $data);
return $query->row();
controller :
public function updateRequest(){
$id = $_POST['id'];
$jenis_request = $_POST['jenis_request'];
$keluhan = $_POST['keluhan'];
$row = $this->model_request->updateRequest($id, $jenis_request, $keluhan );
echo json_encode($row);
}
This is the view using ajax
$('#btn-footer').click(function(e) {
e.preventDefault();
var id = $("#mainTitle strong").text().split("/").pop();
/*get value checkbox*/
var jenis_request = [];//console.log($("input[name='request[]']"));
$("input[name='request[]']:checked").each(function() {
//console.log($(this).val());
jenis_request .push($(this).val());
});
jenis_request = jenis_request.join(',');
alert(jenis_request); //for check
/*ambil keluhan*/
var keluhan = $('#modalkeluhan').val();
$.ajax({
url: '<?php echo base_url() . 'control_closing/updateRequest/' ?>',
type : 'POST',
data : {id : id ,
jenis_request : jenis_request,
keluhan : keluhan
},
dataType: 'json',
success: function (obj) {
console.log(obj);
}
});
});
I got this error, Call to a member function row() on a non-object ,
I know that row() is an object, is that a problem ?
This may help you
public function updateRequest($id_request, $jenis_request, $keluhan )
{
$data= array(
'jenis_request' => $jenis_request,
'keluhan' => $keluhan
);
$this->db->where('id_request', $id_request);
$query = $this->db->update('tbl_requestfix', $data);
$affected_rows=$this->db->affected_rows();
if($affected_rows >0)
{
return $affected_rows." rows updated";//return here the way you want
}
else
{
return "No updates";
}
}