How to modify a controller variable? - codeigniter

There is a variable sent by a controller :
public function ajout()
{
$data = array();
$data['_mode'] = MODE_AJOUT;
$this->load->view('mission/mission', $data);
}
In the view I want to change the variable $_mode to have a value MODE_MODIF ( a constant from the constants.php config file ) after submitting a form by ajax:
$("#form_sample_1").on("submit", function(){
var url_ = "<?php echo ( $_mode == MODE_AJOUT ? site_url('ajax/ajouterMission') : site_url('ajax/modifierMission') ); ?>";
$.ajax({
data: $(this).serialize(),
type: "POST",
url: url_,
async: false,
success: function (data, textStatus, jqXHR ) {
alert("Donn\351es enregistr\351es !");
}
});
return false;
});
How to do that ? or is that impossible ?

Add atribute .
MY_Class Extends CI_Controller{
private $_mode;
}
public function ajout(){
$data = array();
$data['_mode'] = MODE_AJOUT;
$this->load->view('mission/mission', $data);
}
//Call this function with ajax
public checkForm(){
$this->_mode = $newValue; //set attribute
$data['_mode'] = $this->_mode; //get attribute
echo json_encode($data);
}

Related

how to create a new div of json response array from controller

I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}

Applying Ajax (Codeigniter)

I have this script and i need to apply ajax on it. Can someone give me an idea on how to apply ajax on these codes? I need to pass those variables on the controller. It works just fine but i need to alter it into ajax. It's just, im having a hard time figuring it out, how i can reassemble to ajax. Thank you ♥
function saveData(){
var id = $('#id').val()
var name = $('#nm').val()
var slug = $('#em').val()
var books = $('#hp').val()
var address = $('#ad').val()
$.post('<?php echo site_url("welcome/add") ?>', {id:id, nm:name, em:slug, hp:books, ad:address}, function(data){
viewData()
$('#id').val(' ')
$('#nm').val(' ')
$('#em').val(' ')
$('#hp').val(' ')
$('#ad').val(' ')
})
}
function editData(id, nm, em, hp, ad) {
$('#id').val(id)
$('#nm').val(nm)
$('#em').val(em)
$('#hp').val(hp)
$('#ad').val(ad)
$('#id').prop("readonly",true);
$('#save').prop("disabled",true);
$('#update').prop("disabled",false);
}
function updateData(){
var id = $('#id').val()
var name = $('#nm').val()
var slug = $('#em').val()
var books = $('#hp').val()
var address = $('#ad').val()
$.post('<?php echo site_url("welcome/update") ?>', {id:id, nm:name, em:slug, hp:books, ad:address}, function(data){
viewData()
$('#id').val(' ')
$('#nm').val(' ')
$('#em').val(' ')
$('#hp').val(' ')
$('#ad').val(' ')
$('#id').prop("readonly",false);
$('#save').prop("disabled",false);
$('#update').prop("disabled",true);
})
}
function deleteData(id){
$.post('<?php echo site_url("welcome/remove") ?>', {id:id}, function(data){
viewData()
})
}
function removeConfirm(id){
var con = confirm('Are you sure to delete this data? HUHHHHH?!');
if(con=='1'){
deleteData(id);
}
}
$(".clicker").on("click", function(){
$(this).siblings().slideToggle('normal');
})
$(function() {
var $sidebar = $("#sidebar"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 15;
$window.scroll(function() {
if ($window.scrollTop() > offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
});
} else {
$sidebar.stop().animate({
marginTop: 0
});
}
});
});
</script>
Controller:
<?php
header('Access-Control-Allow-Origin: *');
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('crud_model');
}
public function index()
{
$data['books'] = $this->crud_model->getBooks();
$this->load->view('header');
$this->load->view('welcome_message',$data);
$this->load->view('footer');
}
public function view()
{
$data['books'] = $this->crud_model->getBooks();
$data['crud']=$this->crud_model->getView();
$this->load->view('view_data',$data);
}
public function add()
{
$data = array(
'id' => $this->input->post('id'),
'title' => $this->input->post('nm'),
'slug' => $this->input->post('em'),
'book_id'=>$this->input->post('hp'),
);
// $insert = $this->crud_model->postNew($data);
$data2 = array(
'book_id'=>$this->input->post('hp'),
'faqs_id' =>$this->crud_model->postNew($data),
);
$insert1 = $this->crud_model->postNewBridge($data2);
}
public function update()
{
$data = array(
'title' => $this->input->post('nm'),
'slug' => $this->input->post('em'),
'book_id'=>$this->input->post('hp'),
);
$this->crud_model->postUpdate(array('id' => $this->input->post('id')), $data);
}
public function remove()
{
$id = $this->input->post('id');
$this->crud_model->getDelete($id);
}
}
Model:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Crud_model extends CI_Model{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function getBooks()
{
$this->db->select('*');
$this->db->from('book');
$query=$this->db->get();
return $query->result();
}
public function getView()
{
$this->db->select('*');
$this->db->from('book');
$this->db->join('faqs', 'book.id = faqs.book_id','inner');
$query=$this->db->get();
return $query->result();
}
public function postNew($data)
{
$this->db->insert('faqs', $data);
return $this->db->insert_id();
}
public function postNewBridge($data2)
{
$this->db->insert('book_faqs', $data2);
return $this->db->insert_id();
}
public function postUpdate($where, $data)
{
$this->db->update('faqs', $data, $where);
return $this->db->affected_rows();
}
public function getDelete($id)
{
$this->db->where('id', $id);
$this->db->delete('faqs');
}
}
Try this, Here I m giving you only saveData() in ajax
function saveData(){
var id = $('#id').val()
var name = $('#nm').val()
var slug = $('#em').val()
var books = $('#hp').val()
var address = $('#ad').val()
$.ajax({
beforeSend: function () {
//do something before ajax call
},
complete: function () {
//do something after ajax call done
},
type: "POST",
url: '<?php echo site_url('your_contoller/your_function'); ?>/',
data: ({id: id, nm: nm, em: em,hp: hp,ad: ad}),
success: function (data) {
setTimeout(function () {
//do something after a second
}, 1000);
}, error: function (data) {
}
});
}
i hope this helps
You simply need get() with your current code. Just use this function to call page and load it in a container with a class result with ajax.
$('#buttonId').click(function() {
$.get( "controller/function", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
});

codeigniter foreach not displaying all records in table

Hi I am able to retrieve data from a specific table using codeigniter ajax but i don't see everything.
It's simply a chat system I implemented allowing users to send messages to one another.
Everytime a new record is inserted, the latest record does not show up but the previous ones do.
Please see my code attached with this.
Thank you.
Controller - Chats.php
public function ajax_get_chat_messages()
{
echo $this->_get_chat_messages();
}
public function _get_chat_messages()
{
$recipient = $this->input->post('recipient');
$chat = $this->Chats_model->get_chat_messages($recipient);
if($chat->num_rows() > 0)
{
$c_html = '<ul>';
foreach($chat->result() as $cht)
{
$c_html .= '<li>'.$cht->username.'</li>';
$c_html .= '<p>'.$cht->chat_message_content.'</p><hr><br>';
}
$c_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $c_html);
return json_encode($result);
}
}
JS - Chat2.js
$(document).ready(function () {
setInterval(function () { get_chat_messages();}, 2500)
function get_chat_messages()
{
$.post(base_url + "user/chats/ajax_get_chat_messages", {recipient: recipient}, function (data) {
if (data.status == 'ok')
{
$("div#view").html(data.content);
} else
{
//there was an error do something
}
}, "json");
}
/*function get_chat_messages() {
$.ajax({
type: "POST",
dataType: 'json',
url: base_url +"user/chats/ajax_get_chat_messages",
data: {recipient: recipient}, // pass it as POST parameter
success: function(data){
$("div#view").html(data);
console.log(data);
}
});
} */
get_chat_messages();
});
model - Chats_model.php
public function get_chat_messages($recipient)
{
$session = $this->session->userdata('user_id');
$query = "SELECT * FROM chat_messages cm JOIN users u on u.user_id = cm.user_id where cm.user_id = $session and cm.recipient = $recipient or cm.user_id = $recipient and cm.recipient = $session ORDER BY cm.chat_message_id ASC ";
$result = $this->db->query($query, array($recipient));
return $result;
}
Image also attached

populating dropdown based in first selection

My COntroller
public function gettestRecieve() {
$test = array('recieve' => $this->input->post('recieve'));
$data = $this->test->getrecieve($test);
echo json_encode($data);
}
My Model
function getAcademic($test) {
$this->db->select('a_y');
$this->db->where($test);
$this->db->distinct();
$result = $this->db->get('table');
$return = array();
if($result->num_rows() > 0){
$return[''] = 'select';
foreach($result->result_array() as $row){
$return[$row['a_y']] = $row['a_y'];
}
}
return $return;
}
My view
$(document).ready(function () {
$('#test').change(function () {
var add = $(this).val();
//console.log(add);
$.ajax({
url: "<?php echo base_url();?>getAcademic",
method: "POST",
data: {testing: add},
success: function(add) {
var data = JSON.parse(add);//parse response to convert into onject
console.log(data);//see your result in console
//alert(data[0].Ayear);
$('#good').html('<option value="'+ Ayear +'" >'+ Ayear +'</option>');
}
})
});
});
this gives me an error object HTMLSelectElement what does it mean, when i tried to look at my console it gives me a right value {"": "A & Y", 2014-2015: "2014-2015"} but in frontend gives an error, how could i fix this! can someone know this error, thanks and advanced

Select2 not returning any data, just display searching

i'm using codeigniter and select2 plugin for displaying my data.. but i have a problem, that plugin not display anything, just display searching... there is my code
/*------------- JS -----------------*/
$("‪#‎nm_peg‬").select2({
placeholder: "Masukkan Nama Pegawai",
width:'element',
ajax : {
url : "<?php echo site_url('pegawai/getAllData'); ?>",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
this is my controller
/*-------------- Controller ---------------*/
public function getAllData()
{
$this->load->model('pegawaimodel');
$d = $this->pegawaimodel->get_all_pegawai();
$rows = array();
foreach ($d as $a) {
$rows[] = $a;
}
header('Content-Type:application/json');
return json_encode($d);
}
and this is my model.
/*--------------Model-----------------*/
public function get_all_pegawai()
{
$this->db->select('peg_id, peg_nama');
$this->db->from('master_pegawai');
$query = $this->db->get();
return $query->result();
}
thank's for any help..

Resources