Applying Ajax (Codeigniter) - ajax

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." );
});
});

Related

Laravel: Post Array of Objects

Im in trouble with this code, I cant store my dataP array objects into mysql.
Ajax request :
$.ajax({
url:'/register/addpostulantR',
method:'post',
dataType: "text",
data:JSON.stringify(dataP),
success(data){
console.log("succ "+data);
},
error:()=>{
console.log('error ');
}
})
Controller:intervenantController.php
public static function addPostulantR(Request $request)
{
return response()->json([
'dataP' => Intervenant::addPostulantR($request->all())
]);
//The dataP is my json
}
Model: Intervenant.php
public static function addPostulantR($data)
{
//$test = json_decode($data);
$id = 0;
foreach($data as $dataP) {
$id = DB::table('reponse')->insertGetId($dataP);
}
return $id;
}
Array: From my javascript
let dataP = [
{
fk_id_quest:1,
fk_id_post:id,
reponse : $("#descriptif_offre").val(),
created_at:date.getTime()/1000,
},
{
fk_id_quest:2,
fk_id_post:id,
reponse : $("#descriptif_offre").val(),
created_at:date.getTime()/1000,
}
];
Thanks a lot..

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

How to modify a controller variable?

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);
}

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..

Unable to populate dropdown with ajax in codeigniter

http://rimi-classified.com/ad-list/west-bengal/kolkata/electronics-and-technology
The above link has a filter in the left. I am trying to use ajax to get city from state. but as the ajax is triggered the entire query is changing.
SELECT * FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'pages'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
It is taking the controller name in the query (controller name is pages).
The actual query is:
SELECT *
FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'electronics-and-technology'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
// Controller
public function ad_list($state,$city,$category,$sub_cat=FALSE)
{
if($state===NULL || $city===NULL || $category===NULL)
{
redirect(base_url());
}
if ($sub_cat === FALSE)
{
$data['ad_list'] = $this->home_model->get_adlist($state,$city,$category);
}
$data['ad_list'] = $this->home_model->get_adlist($state,$city,$category,$sub_cat);
$this->load->view('templates/header1', $data);
$this->load->view('templates/search', $data);
$this->load->view('ad-list', $data);
$this->load->view('templates/footer', $data);
}
public function get_cities()
{
$state_id = $this->input->post('state');
echo $this->city_model->get_cities($state_id);
}
// home Model
public function get_adlist($state,$city,$category,$sub_cat=FALSE)
{
if ($sub_cat === FALSE)
{
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
}
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('sub_cat_slug', $sub_cat);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
return $query->result_array();
//echo $this->db->last_query();
}
//state model
class State_model extends CI_Model {
public function __construct() {
$this -> load -> database();
}
function get_states() {
$query = $this->db->order_by('state', 'ASC')->get('state');
return $query->result_array();
}
}
//city model
class City_model extends CI_Model {
public function __construct() {
$this -> load -> database();
//$this->output->enable_profiler(TRUE);
}
function get_cities($state){
if($state != NULL){
$this->db->where('state_id', $state);
$query = $this->db->get('city');
$cities = array();
$html = '';
if($query->result())
{
$html .= '<select id="city_id" name="city_id">';
$html .= '<option value="">-- Select City --</option>';
foreach ($query->result() as $city)
{
$html .= '<option value="'.$city->id .'">'.$city->city.'</option>';
}
$html .= '</select>';
return $html;
}
else
{
return FALSE;
}
}
else
{
$html = '<option value="">--Select City--</option>';
return $html;
}
}
}
//ajax
<script type="text/javascript">
$(document).ready(function () {
$('#state_id').change(function () {
var selState = $(this).val();
alert(selState);
console.log(selState);
$.ajax({
url: "pages/get_cities",
async: false,
type: "POST",
data : "state="+selState,
dataType: "html",
success: function(data) {
$('#city').html(data);
$("#location_id").html("<option value=''>--Select location--</option>");
}
})
});
});
</script>
Please help me how to solve this issue. Please check the url I have provided and try to select a state from the filter section the problem will be more clear.
try this in controller
public function get_cities()
{
$state_id = $this->input->post('state');
$cities = $this->city_model->get_cities($state_id);
echo '<option value="">-- Select City --</option>';
foreach($cities as $city){
echo '<option value="'.$city->id .'">'.$city->city.'</option>';
}
}
in model
function get_cities($state){
$this->db->where('state_id', $state);
$query = $this->db->get('city');
return $query->result();
}
in ajax
success: function(data) { $('#city_id').html(data)}

Resources