Polling Chat message content to screen using ajax JSON - ajax

Hi I successfully designed a chat message system between users and it works fine. The only problem I am having at this point is polling data from chat table to browser real time.
The messages are displayed using ajax and the setInterval works as I checked the console. The issue is that it does not capture new entries to the table for display and hence the user has to keep refreshing the page to see new content.
Please help. My code is below. Please forgive my file naming convention as I will change it later on.
PS this is developed using codeigniter framework.
**Chats.php - Controller**
public function ajax_get_chat_messages(){
echo $this->_get_chat_messages();
}
function _get_chat_messages($recipient = null)
{
$user_id = $this->session->userdata('user_id');
$recipient = $this->input->post('recipient');
$data['recipient'] = $this->User_model->get_users($user_id);
$data['chats_count'] = $this->Chats_model->get_chat_messages_count($recipient);
$content = $this->Chats_model->get_chat_messages_count($recipient);
$data['chats'] = $this->Chats_model->get_chat_messages($user_id);
$result = array('status' =>'ok', 'content'=>$content);
return json_encode($result);
}
**Model - Chats_model.php**
public function get_chat_messages_count($recipient = null){
$session = $this->session->userdata('user_id');
$this->db->select('*');
$this->db->from('chat_messages');
$this->db->join('users', 'users.user_id = chat_messages.user_id');
$this->db->where(array('chat_messages.user_id' => $session));
$this->db->where(array('chat_messages.recipient' => $recipient));
$this->db->or_where(array('chat_messages.user_id' => $recipient));
$this->db->where(array('chat_messages.recipient' => $session));
$this->db->where_in(array('chat_messages.chat_id' => $session , $recipient));
$query = $this->db->get();
return $query->result_array();
}
**View - chats_view.php**
<script type="text/javascript">
var user = "<div class='timeline-item' id='view'><ul><?php foreach($chats_count as $chat){echo '<li>'; echo $chat['username']; echo '</li>'; }?></ul></div>";
</script>
<div class="wrapper wrapper-content">
<div class="row animated fadeInRight">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>Chat</h5>
<div class="ibox-tools" >
</div>
</div>
<div class="ibox-content inspinia-timeline" id="view1" >
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
**JS - chat2.js**
$(document).ready(function(){
setInterval(function() { get_chat_messages(); }, 2500)
$("input#chat_message").keypress(function(e){
if(e.which == 13){
$("a#submit_message").click();
return false;
}
});
function get_chat_messages(){
$.post(base_url +"user/chats/ajax_get_chat_messages",{user: user}, function(data) {
if(data)
{
var current_content = $("#view1").html();
$("#view1").html(user);
console.log(user);
}
else
{
}, "json");
}
get_chat_messages();
});
Images attached showing the table structure, the chat page on browser and console data.
[Chat page on browser, only showing username for testing purposes][1]
[Chat Table][2]
[Console Data, only showing username for testing purposes][3]

Related

how to add alert in to login my login page like "login successfully"?

I have login page but i am dont know where i can take this alerts ,
i will take my script like this
echo ("<SCRIPT LANGUAGE='JavaScript'> window.alert('Your Login Succesfully ,'); window.location.href='home'; </SCRIPT>");
but i dont know how to make if else condition on my query in the model and contoller .I using num_rows but its didnt work .
my controller
public function login()
{
$u = $this->input->post('username');
$p = $this->input->post('password');
$data = $this->app_model->getlogindata($u,$p);
return $data;
}
my model
public function getlogindata($username,$password)
{
$u = $username;
$p = md5($password);
$cek_login = $this->db->get_where('login', array('username' => $u,'password'=>$p));
if(count($cek_login->result())>0)
{
foreach ($cek_login->result() as $qck)
{
if($qck->level=='puskesmas')
{
// $ambil_data = $this->db->get_where('puskesmas',array('id_puskesmas' => $u));
$this->db->select('*');
$this->db->from('puskesmas');
$this->db->join('login', 'puskesmas.id_puskesmas=login.id_puskesmas');
$this->db->where('username', $u);
$ambil_data = $this->db->get();
foreach ($ambil_data->result() as $qad)
{
$sess_data['logged_in'] = 'yes';
$sess_data['id_puskesmas'] = $qad->id_puskesmas; //
$sess_data['nama_puskesmas'] = $qad->nama_puskesmas;
$sess_data['alamat_puskesmas'] = $qad->alamat_puskesmas;
$sess_data['nama_petugas'] = $qad->nama_petugas;
$sess_data['nomor'] = $qad->nomor;
$sess_data['email'] = $qad->email;
$sess_data['level'] = $qad->level;
$this->session->set_userdata($sess_data);
}
header('location:'.base_url().'puskesmas');
} //xammp mu aktif?
elseif($qck->level=='dinas')
{
//$ambil_data = $this->db->get_where('dinas',array('id_dinas' => $u));
$this->db->select('*');
$this->db->from('dinas');
$this->db->join('login', 'dinas.id_dinas=login.id_dinas');
$this->db->where('username', $u);
$ambil_data = $this->db->get();
foreach ($ambil_data->result() as $qad)
{
$sess_data['logged_in'] = 'yes';
$sess_data['id_dinas'] = $qad->id_dinas;
$sess_data['nama_dinas'] = $qad->nama_dinas;
$sess_data['alamat_dinas'] = $qad->alamat_dinas;
$sess_data['kode_pos'] = $qad->kode_pos;
$sess_data['level'] = $qad->level;
$this->session->set_userdata($sess_data);
}
header('location:'.base_url().'dinas');
}
elseif($qck->level=='admin')
{
//$ambil_data = $this->db->get_where('admin',array('id_admin' => $u));
$this->db->select('*');
$this->db->from('admin');
$this->db->join('login', 'admin.id_admin=login.id_admin');
$this->db->where('username', $u);
$ambil_data = $this->db->get();
foreach ($ambil_data->result() as $qad)
{
$sess_data['logged_in'] = 'yes';
$sess_data['id_admin'] = $qad->id_admin;
$sess_data['nama_admin'] = $qad->nama_admin;
$sess_data['alamat_admin'] = $qad->alamat_admin;
$sess_data['status'] = $qad->status;
$sess_data['level'] = $qad->level;
$this->session->set_userdata($sess_data);
}
header('location:'.base_url().'admin');
}
else{
echo ("<SCRIPT LANGUAGE='JavaScript'> window.alert('Record Updated Successfully'); window.location.href='web'; </SCRIPT>");// i add this and still didnt work
}
}
}
}
in this script i just didnt know where i can take this alerts and what a parameter can i use to add this alerts . like if num_rows = 1 , echo = blablabla
thanks you sir
you have to use flash data in code igniter or you can use ajax callback in success you can alert what you want and redirect to whatever you like.
Controller
$this->session->set_flashdata('error_message', 'Incorrect Username or Password ! Please try again.');
redirect(URL.'backend/login');
View
<?php
if ($this->session->flashdata('error_message'))
{
?>
<div class="alert alert-danger" style="color: #fff;">
<!-- <button class="close" data-close="alert"></button> -->
<span><?php echo $this->session->flashdata('error_message'); ?></span>
</div>
<?php
}
if ($this->session->flashdata('ok_message'))
{
?>
<div class="alert alert-success">
<!-- <button class="close" data-close="alert"></button> -->
<span><?php echo $this->session->flashdata('ok_message'); ?></span>
</div>
<?php
}
?>
try this.i hope it will help you.
else{
echo '<script language="javascript">';
echo 'alert("Record Updated Successfully")';
window.location.href = 'web';
echo '</script>';
}

How to Set or retrieve old Path image when we not update the image in the form multiple images in Codeigniter 2.2.6

I have edit form in codeigniter in that form i have 15 more image file while i update the image it updating in database but even am not update the images in the form it goes and save as null or empty path .But i need solution for that when am not update all 15 files should retrive the same old image path which it is stored in database.Please Could you guys give better solution for this.
My Edit Form
controller:
if($this->input->post('submit'))
{
if($_FILES['file']['name']!='')
{
$filename = $_FILES['file']['name'];
$file_name1 = "upload_".$this->get_random_name()."_".$filename;
$_SESSION['file_upload']=$file_name1;
$file ="uploads/images/".$file_name1;
}
if($_FILES['file1']['name']!='')
{
$filename = $_FILES['file1']['name'];
$file_name2 = "upload_".$this->get_random_name()."_".$filename;
$_SESSION['file_upload']=$file_name2;
$file ="uploads/images/".$file_name2;
}
$query = $this->scener_model->popular_upload($file_name1,$file_name2)
}
If your is empty then pass hidden input value or else pass newly uploaded value like this..
if(!empty($_FILES()){
//your uploaded value here
} else {
//hidden attribute value
}
if($this->input->post('submit1')){
$titlemain = $this->input->post('title_main');
$price = $this->input->post('price');
$package = $this->input->post('package');
$titleinner = $this->input->post('title_inner');
$city_package = $this->input->post('city_packge');
if(!empty($count =count($_FILES['file1']['name']))){;
for($i=0; $i<$count;$i++){
$filename1=$_FILES['file1']['name'][$i];
//print_r($filename);exit;
$filetmp=$_FILES['file1']['tmp_name'][$i];
$filetype=$_FILES['file1']['type'][$i];
$images = $_FILES['file1']['name'];
$filepath="uploads/images/".$filename1;
move_uploaded_file($filetmp,$filepath);
}
$filename1 = implode(',',$images);
}
else{
$filename1=$this->input->get('iti_image2') ;
//print_r( $data['newz1']);exit;
}
my view page:
<div class="col-sm-8">
<input type="button" id="get_file" value="Grab file">
<?php
$imss= $result->iti_image2;
?>
<input type="file" id="my_file" name="file3[]" value="<?php echo $imss ?>" multiple/>
<div id="customfileupload">Select a file</div>
<input type="hidden" class="btn btn info" id="image" name="iti_image2" accept="image" value="<?php echo $result->iti_image2; ?>" multiple/ >
</div>
<script>
document.getElementById('get_file').onclick = function() {
document.getElementById('my_file').click();
};
$('input[type=file]').change(function (e) {
$('#customfileupload').html($(this).val());
});
</script>
</div>
my Model:
function itinerary_updte($filename4,$filename5){
$update_itinerarys = array(
'iti_image2' =>$filename4,
'iti_image3' =>$filename5
);
$this->db->where('id', $id);
$result = $this->db->update('sg_itinerary', $update_itinerarys);
return $result;
}
Finally guys i found a solution for image updating follwing some tutorials see the link
"http://www.2my4edge.com/2016/04/multiple-image-upload-with-view-edit.html"
thanks buddies who are give the logic and commenting on my post and thanks alot #ankit singh #Lll

$_FILES['imagem'] is undefined in Firefox

My website is built using Codeigniter, and there's an area for users to modify their information. This area allows users to choose a profile picture, and when editing it, the selected picture is previewed. In case they don't choose a new one, there's a hidden field storing its name, which is passed to the controller to specify the same image name, but if the user decides to change it, the new name is passed to the controller.
public function edit($id)
{
$this->input->post('tipo_usuario') === 'F' ? $validator = 'editar_pessoa_fisica' : $validator = 'editar_pessoa_juridica';
if ($this->form_validation->run($validator)) {
$data = array();
$data['nome_razao_social'] = $this->input->post('nome_razao_social');
$data['nome_responsavel'] = $this->input->post('nome_responsavel');
$data['nome_fantasia'] = $this->input->post('nome_fantasia');
$data['cpf_cnpj'] = $this->input->post('cpf_cnpj');
$data['telefone'] = $this->input->post('telefone');
$data['telefone_2'] = $this->input->post('telefone_2');
$data['email'] = $this->input->post('email');
$data['novo_email'] = $this->input->post('novo_email');
$data['senha'] = md5($this->input->post('senha'));
$data['cep'] = $this->input->post('cep');
$data['logradouro'] = $this->input->post('logradouro');
$data['id_cidade'] = $this->input->post('id_cidade');
$data['id_estado'] = $this->input->post('id_estado');
$data['numero'] = $this->input->post('numero');
$data['complemento'] = $this->input->post('complemento');
$data['tipo_usuario'] = $this->input->post('tipo_usuario');
/*
HERE IS IN CASE THE USER DOES NOT CHANGE HIS PROFILE PICTURE
*/
$data['imagem'] = $this->input->post('imagem_old');
$data['url'] = $this->input->post('url');
// Nova senha?
if ($this->input->post('novasenha') !== '') {
$data['senha'] = md5($this->input->post('novasenha'));
} else {
$data['senha'] = $this->input->post('senha');
}
/*
HERE IS IN CASE THE USER CHANGES HIS PROFILE PICTURE
*/
// Nova imagem?
if ($_FILES['imagem']['name'] !== '') {
$data['imagem'] = $_FILES['imagem']['name'];
}
// Novo e-mail?
if ($this->input->post('email') !== $this->input->post('novoemail')) {
$data['novo_email'] = $this->input->post('novoemail');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->input->post('novo_novo_email') !== $this->input->post('novo_email')) {
$data['novo_email'] = $this->input->post('novo_novo_email');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->Usuarios_model->update($data, $id)) {
$this->upload->do_upload('imagem');
$this->session->set_flashdata('message', 'Dados alterados');
echo json_encode(array(
'redirect' => '/usuario/painel'
));
}
} else {
echo json_encode(array(
'type' => 'validation',
'message' => validation_errors(),
));
}
}
This is the HTML:
<form action="/auto/usuario/edit/<?php echo $id_usuario; ?>" method="POST" class="formulario" enctype="multipart/form-data">
<input type="hidden" name="tipo_usuario" value="F"/>
<div class="p100">
<span class="titulo">Foto de Perfil</span>
<div class="imagem_destaque img_perfil image-trigger">
<div class="file-upload-trigger">
<input type="file" name="imagem" class="none file-chooser"/>
<img src="/uploads/perfil/<?php echo $u['imagem'] ?>" class="preview more"/>
</div>
</div>
<input type="hidden" name="imagem_old" value="<?php echo $u['imagem']; ?>"/>
</div>
With Google Chrome, it works fine, but in Firefox 45, if I do not choose a new image, an error is thrown:
Severity: Notice
Message: Undefined index: imagem
Filename: controllers/Usuario.php
Line Number: 362
It only works locally.
If you do not upload a new image, your $_FILES[] is undefined, as the error says. To check if the user has changed his image you should do:
if ( isset($_FILES['imagem']['name']) ) {
$data['imagem'] = $_FILES['imagem']['name'];
}

selectbox doesn't change by ajax

I have ajax code that display the name of the cities(in selectbox) according the area that has been chosen:
<?PHP if ($_POST) { ?>
$(document).ready(function(){
$('#areaID').filter(function(){
var areaID=$('#areaID').val();
var cityID=<?PHP echo $cityID ?>;
$('#cityID').load('js/ajax/getCities.php?areaID=' + areaID+'&cityID=' + cityID);
return false;
});
});
<?PHP }else { ?>
$(function () {
function updateCitySelectBox() {
var areaID = $('#areaID').val();
$('#cityID').load('js/ajax/getCities.php?areaID=' + areaID);
return false;
}
updateCitySelectBox();
$('#areaID').change(updateCitySelectBox);
});
<?PHP } ?>
The problem is - after user submit the form and get error (i.e - forget to fill some field), user can change the area but the cities select box doesn't change according the new area.
What is wrong with the code?
<p><label>area</label>
<select name='areaID' id='areaID'>
<?PHP
$query = mysql_query("SELECT * FROM `areas` ORDER BY id ASC ");
while($index = mysql_fetch_array($query))
{
$db_area_id = $index['id'];
$db_area_name = $index['name'];
if ($db_area_id == $areaID)
echo "<option value='$db_area_id' selected>$db_area_name</option>";
else
echo "<option value='$db_area_id'>$db_area_name</option>";
}
?>
</select><span>*</span>
</p>
<p><label>City</label>
<select id='cityID' name='cityID'> </select>
</p>

Ajax Pagination Error in codeigniter

i have the following code which i modiefied from a tutorial
but the problem is that, i cant display the result properly in my view page..
if i display the array in the controller then its working properly, but in the view, its throwing the error..
<?php
class test extends CI_Controller {
public function index($start = 0) {
$this->load->model('pages_model');
$data_page=$this->pages_model->get_pages();
$this->load->helper('url');
$this->load->library('pagination');
$config['base_url'] = base_url().'test/index';
$config['total_rows'] = count($data_page);
$config['per_page'] = 5;
$data['user'] = array();
for($i=$start; $i<$start+$config['per_page']; $i++)
{
if (isset($data_page[$i])) {
$data['user'] = $data_page[$i];
}
}
//print_r($data['user']['page_id']); // this line displays 3, since the tupple with id 3 has maximum priority 5
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
if ($this->input->post('ajax')) {
$this->load->view('test', $data);
} else {
$this->load->view('test', $data);
}
}
}
?>
now comes the model
<?php
class pages_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_pages()
{
return $this->db->query("SELECT * FROM td_pages ORDER BY page_priority ASC")->result_array();
}
}
?>
and finally the view
<!DOCTYPE html>
<html>
<header>
<title>CodeIgniter Ajax Jquery Pagination</title>
<script src="<?php echo base_url(); ?>assets/front_assets/js/jquery-1.7.1.min.js"></script>
<script>
$(function() {
applyPagination();
function applyPagination() {
$("#ajax_paging a").click(function() {
var url = $(this).attr("href");
$.ajax({
type: "POST",
data: "ajax=1",
url: url,
beforeSend: function() {
$("#content").html("");
},
success: function(msg) {
$("#content").html(msg);
applyPagination();
}
});
return false;
});
}
});
</script>
</header>
<body>
<div id="content">
<div id="data">
<?php foreach($page_frag as $ut)
{?>
<div><?php echo $ut['page_slug'];?></div>
<?php } ?>
</data>
<div id="ajax_paging">
<?php echo $pagination; ?>
</div>
</div>
</div>
</body>
</html>
the problem is that the view is displaying the results in wrong way, but if i display in controller, then it shows that the array in the controller is working perfectly...
please help me solving the prob
You are loading the entire view in your ajax request which also contains the body and head text, Create a seperate view with the following content and load it in your ajax request.
<div id="data">
<?php foreach($page_frag as $ut)
{?>
<div><?php echo $ut['page_slug'];?></div>
<?php } ?>
</div>
What you're doing is WRONG
Pagination is meant to off-load processing power/ram from the server not only from the client side.
You're pulling off all your result then paginate them while you should be asking MySQL to paginate it for you & have a second query to give you the number of results to use it.
If you have index.php in your links then you must be using site_url() instead of base_url() & please note that both accepts an argument so you do not need to concatenate it the way you did it would be like this:
site_url('test/index');
codeigniter uses GET method, while in your javascript code you're using POST.
An easier method would be to catch the pagination li > a tags for the pagination & process it inside a container.

Resources