Hi this question relates to a recent question I had posted that I'm trying to find at least some help with in general that leads to solve the entire problem.
The following code is not mine and I had to fix it just to get it working to the extent it is now but the problem the algorithm within _get_chat_messages continues to execute the else condition. This doesn't make sense because there's chat message data in Mysql. I'm trying to make this source code work hoping it will lead me in the right direction with refreshing chat message content automatically without forcing browser client refreshes or redirecting headers.
What's causing _get_chat_messages to execute the else condition disregarding the if condition. The if conditions seems to evaluate to TRUE which doesn't make sense.
Any help much appreciated. Thanks.
//JQUERY/AJAX:
$(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;
}
});
$("#submit_message").click(function() {
var chat_message_content = $("input#chat_message").val();
//this if condition seems to be ignored not sure why?
if (chat_message_content == "") { return false; }
$.post(base_url + "chat/ajax_add_chat_message", { chat_message_content : chat_message_content, chat_id : chat_id, user_id : user_id }, function(data) {
if (data.status == 'ok')
{
var current_content = $("div#chat_viewport").html();
$("div#chat_viewport").html(current_content + data.message_content);
}
else
{
// there was an error do something
}
}, "json");
$("input#chat_message").val("");
return false;
});
function get_chat_messages()
{
$.post(base_url + "chat/ajax_get_chat_messages", { chat_id : chat_id }, function(data) {
if (data.status == 'ok')
{
var current_content = $("div#chat_viewport").html();
$("div#chat_viewport").html(current_content + data.message_content);
}
else
{
// there was an error do something
}
}, "json");
}
get_chat_messages();
});
//CONTROLLER:
class Chat extends CI_Controller {
public function __construct()
{
parent:: __construct();
$this->load->model('chat_model');
}
public function index()
{
/* send in chat id and user id */
$this->view_data['chat_id'] = 1;
// check they are logged in
if (! $this->session->userdata('logged_in')) {
redirect('user/login');
}
$this->view_data['user_id'] = $this->session->userdata('user_id');
$this->session->set_userdata('last_chat_message_id_' . $this->view_data['chat_id'], 0);
$this->view_data['page_title'] = 'web based chat app :)';
$this->view_data['page_content'] = 'view_chat';
$this->load->view('view_main', $this->view_data);
}
public function ajax_add_chat_message()
{
/* Scalar Variable data that needs to be POST'ed to this function
*
* chat_id
* user_id
* chat_message_content
* *
*/
$chat_id = $this->input->post('chat_id');
$user_id = $this->input->post('user_id');
$chat_message_content = $this->input->post('chat_message', TRUE);
$this->chat_model->add_chat_message($chat_id, $user_id, $chat_message_content);
// grab and return all messages
$this->ajax_get_chat_messages($chat_id);
}
public function ajax_get_chat_messages($chat_id)
{
$chat_id = $this->input->post('chat_id');
echo $this->_get_chat_messages($chat_id);
}
private function _get_chat_messages($chat_id)
{
$last_chat_message_id = (int)$this->session->userdata('last_chat_message_id_' . $chat_id);
$chat_messages = $this->chat_model->get_chat_messages($chat_id, $last_chat_message_id);
if ($chat_messages->num_rows() > 0)
{
// store the last chat message id
$last_chat_message_id = $chat_messages->row($chat_messages->num_rows() - 1)->chat_message_id;
$this->session->set_userdata('last_chat_message_id_' . $chat_id, $last_chat_message_id);
// we have some chat let's return it
$chat_messages_html = '<ul>';
foreach ($chat_messages->result() as $chat_message)
{
$li_class = ($this->session->userdata('user_id') == $chat_message->user_id) ? 'class="by_current_user"' : '';
$chat_messages_html .= '<li ' . $li_class . '>' . '<span class="chat_message_header">' . $chat_message->chat_message_timestamp . ' by ' . $chat_message->name . '</span><p class="message_content">' . $chat_message->chat_message_content . '</p></li>';
}
$chat_messages_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $chat_messages_html);
//header('Content-Type: application/json',true);
return json_encode($result);
exit();
}
else
{
// we have no chat yet
$result = array('status' => 'no chat', 'content' => '');
//header('Content-Type: application/json',true);
return json_encode($result);
exit();
}
}
}
//MODEL:
class chat_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function add_chat_message($chat_id, $user_id, $chat_message_content)
{
$query_str = "INSERT INTO chat_messages (chat_id, user_id, chat_message_content) VALUES (?, ?, ?)";
$this->db->query($query_str, array($chat_id, $user_id, $chat_message_content));
}
public function get_chat_messages($chat_id, $last_chat_message_id = 0)
{
$query_str = "SELECT
cm.chat_message_id,
cm.user_id,
cm.chat_message_content,
DATE_FORMAT(cm.create_date, '%D of %M %Y at %H:%i:%s') AS chat_message_timestamp,
u.name
FROM chat_messages cm
JOIN users u ON cm.user_id = u.user_id
WHERE cm.chat_id = ?
and cm.chat_message_id > ?
ORDER BY cm.chat_message_id ASC";
$result = $this->db->query($query_str, array($chat_id, $last_chat_message_id));
return $result;
}
}
//VIEW FILE HENCE VIEW_CHAT.PHP
<html>
<head>
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<?php echo base_url() . 'public/';?>chat.js">
</script>
<script type="text/javascript">
var base_url = "<?php echo base_url();?>";
var chat_id = "<?php echo $chat_id; ?>";
var user_id = "<?php echo $user_id; ?>";
</script>
</head>
<body>
<style type="text/css">
div#chat_viewport {
font-family:Verdana, Arial, sans-serif;
padding:5px;
border-top:2px dashed #585858;
min-height:300px;
color:black;
max-height:650px;
overflow:auto;
margin-bottom:10px;
width:750px;
}
div#chat_viewport ul {
list-style-type:none;
padding-left:10px;
}
div#chat_viewport ul li {
margin-top:10px;
width:85%;
}
span.chat_message_header {
font-size:0.7em;
font-family:"MS Trebuchet", Arial, sans-serif;
color:#547980;
}
p.message_content {
margin-top:0px;
margin-bottom:5px;
padding-left:10px;
margin-right:0px;
}
input#chat_message {
margin-top:5px;
border:1px solid #585858;
width:70%;
font-size:1.2em;
margin-right:10px;
}
input#submit_message {
font-size:2em;
padding:5px 10px;
vertical-align:top;
margin-top:5px;
}
div#chat_input { margin-bottom:10px; }
div#chat_viewport ul li.by_current_user span.chat_message_header {
color:#e9561b;
}
</style>
<h1>Let's do some chatting :D</h1>
<div id="chat_viewport">
</div>
<div id="chat_input">
<?php echo form_open('chat/ajax_add_chat_message'); ?>
<input id="chat_message" name="chat_message" type="text" value="" tabindex="1" />
<?php echo form_submit('submit_message','submit_message'); ?>
<?php echo anchor('#', 'Say it', array('title' => 'Send this chat message', 'id' => 'submit_message'));?>
<div class="clearer"></div>
<?php echo form_close(); ?>
</div>
</body>
</html>
I am not sure but I have a feeling that the json that you receive from the server is not formatted properly. See this: jQuery won't parse my JSON from AJAX query
Related
If you load XML links into https://www.convertcsv.com/xml-to-csv.htm (by using Enter URL), you immediately get a nice table:
How can you do it directly in PHP without knowing the XML's structure in advance?
Sample code and URL:
<?php
url = 'https://uxdb.s3.amazonaws.com';
$input = new SimpleXMLElement($url, 0, TRUE);
echo '<pre>' . print_r($input, true) . '<pre>';
?>
Which gives you:
Here's how I ended up doing it - https://paiza.io/projects/-ouYa8tFfqcH8QeaVeQfIw (this fiddle tester has a limit on output, so I used 5 instead of count($array) there):
<?php
$url = 'https://uxdb.s3.amazonaws.com';
$input = new SimpleXMLElement($url, 0, TRUE);
$json = json_encode($input);
$array = json_decode($json,TRUE)['Contents'];
header('Content-Type: text/html; charset=utf-8');
?>
<head>
<style>
table2 {
border-spacing: 0;
width: 100%;
border: 1px solid #ddd;
}
th {cursor: pointer;}
th, td {
text-align: left;
padding: 16px;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
</style>
</head>
<body>
<table id="sortable">
<?php
for ($i=0; $i<count($array); $i++) {
if ($i==0)
echo "<thead>\n";
echo "<tr>\n";
foreach ($array[$i] as $key => $value)
echo ($i==0 ? "<th>$key ↕</th>" : "<td>" . ($key == 'Key' ? "$value" : $value) . "</td>") . "\n";
echo "</tr>\n";
if ($i==0)
echo "</thead>\n<tbody>\n";
}
?>
</tbody>
</table>
<script>document.addEventListener('DOMContentLoaded', function() {
const table = document.getElementById('sortable');
const headers = table.querySelectorAll('th');
const tableBody = table.querySelector('tbody');
const rows = tableBody.querySelectorAll('tr');
// Track sort directions
const directions = Array.from(headers).map(function(header) {
return '';
});
// Transform the content of given cell in given column
const transform = function(index, content) {
// Get the data type of column
const type = headers[index].getAttribute('data-type');
switch (type) {
case 'number':
return parseFloat(content);
case 'string':
default:
return content;
}
};
const sortColumn = function(index) {
// Get the current direction
const direction = directions[index] || 'asc';
// A factor based on the direction
const multiplier = (direction === 'asc') ? 1 : -1;
const newRows = Array.from(rows);
newRows.sort(function(rowA, rowB) {
const cellA = rowA.querySelectorAll('td')[index].innerHTML;
const cellB = rowB.querySelectorAll('td')[index].innerHTML;
const a = transform(index, cellA);
const b = transform(index, cellB);
switch (true) {
case a > b: return 1 * multiplier;
case a < b: return -1 * multiplier;
case a === b: return 0;
}
});
// Remove old rows
[].forEach.call(rows, function(row) {
tableBody.removeChild(row);
});
// Reverse the direction
directions[index] = direction === 'asc' ? 'desc' : 'asc';
// Append new row
newRows.forEach(function(newRow) {
tableBody.appendChild(newRow);
});
};
[].forEach.call(headers, function(header, index) {
header.addEventListener('click', function() {
sortColumn(index);
});
});
});</script>
It is a simple application which shows an image based on the input result as well as its occupation and name when hovered. I am receving the following errors:
Notice: Undefined index: src in C:\xampp\htdocs\Ajax\Ajax_image\PHP_AJAX.php and Notice: Undefined index: name in C:\xampp\htdocs\Ajax\Ajax_image\PHP_AJAX.php
I am farely new to Ajax so any help is appreciated.
$(document).ready(function() {
$('#view').click(function() {
var namevalue = $('#name').val();
$.post("PHP_AJAX.php", {
name: namevalue
}, function(data) {
$('#bar').html(data);
$("img").hover(function(e) {
var s1 = "<img src=";
var s2 = " width='110px' height='120px' />";
var srcval = s1.concat($(this).attr('src'), s2);
$.post("PHP_AJAX.php", {
src: srcval
}, function(data1) {
$('#info').css({
top: e.clientY,
left: e.clientX,
backgroundColor: 'yellow'
}).fadeIn().html(data1);
});
}, function() {
$('#info').fadeOut();
});
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="PHP_AJAX.js"></script>
<style>
#info {color:black; border:5px blue solid; width:150px; height:100px;display:none;position:absolute;}
</style>
</head>
<body>
<p id='bar'>Please enter name to view image! </p>
<p id='info'>info</p>
<form>
<p>Name : <input type='text' name='name'id ='name'/></p>
</form>
<button id='view' name ='view'>View</button>
</body>
</html>
class Person
{
// some properties
private $name;
private $occupation;
private $image;
// constructor
public function __construct($nameval, $occuval, $imgval)
{
$this->name = $nameval;
$this->occupation = $occuval;
$this->image = "<img src=" . $imgval . " width='110px' height='120px' />";
}
// get name property
public function getname()
{
return $this->name;
}
// get occupation property
public function getoccupation()
{
return $this->occupation;
}
// get image property
public function getimage()
{
return $this->image;
}
}
$obj1 = new Person("Picasso", "Painter", "pi1.jpg");
$obj2 = new Person("Ronaldo", "Football Player", "ronaldo.jpg");
$obj3 = new Person("Picasso", "Teacher", "pi2.jpg");
$obj4 = new Person("Madonna", "Singer", "madonna.jpg");
// storing objects in an array
$arr = array($obj1, $obj2, $obj3, $obj4);
$count = 0;
for ($i = 0; $i < 4; $i++) {
// if name already exist
if ($arr[$i]->getname() == $_POST['name']) {
echo "<p>Image of " . $arr[$i]->getname() . "</p>";
echo "<p>" . $arr[$i]->getimage() . "</p>";
$count++;
}
if ($arr[$i]->getimage() == $_POST['src']) {
echo "<p>Name: " . $arr[$i]->getname() . "</p>";
echo "<p> Occupation:" . $arr[$i]->getoccupation() . "</p>";
$count++;
}
}
// if name doesn't exist
if ($count == 0) {
echo "<h3> NOT FOUND! </h3>";
}
you should check isset() before compare ex. $arr[$i]->getname() == $_POST['name']
so:
if (isset($_POST['name']) && $arr[$i]->getname() == $_POST['name']) {
...
}
if (isset($_POST['src']) && $arr[$i]->getimage() == $_POST['src']) {
...
}
designing a Facebook like scrolling system the data shows but it does not show the first 5 values and it shows the values in repetition
here is my code:
view:
$(document).ready(function() {
var total_record = 0;
var total_groups = <?php echo $total_data; ?>;
$('#results').load("<?php echo base_url() ?>user/load_more", {'group_no':total_record}, function() {total_record++;});
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height())
{
if(total_record <= total_groups)
{
loading = true;
$('.loader_image').show();
$.post('<?php echo site_url() ?>user/load_more',{'group_no': total_record},
function(data){
if (data != "") {
$("#results").append(data);
$('.loader_image').hide();
total_record++;
}
});
}
}
});
});
then my controller
public function load_more()
{
$group_no = $this->input->post('group_no');
//print_r($group_no);
$content_per_page = 10;
$start = ceil($group_no * $content_per_page);
//print_r($start);
$this->load->model('Pmodel');
$user_id = $this->session->userdata('user_id');
$all_content = $this->Pmodel->get_all_content($user_id,$start,$content_per_page);
// echo '<pre>';
//print_r($all_content);
if(isset($all_content) && is_array($all_content) && count($all_content)) :
foreach ($all_content as $key => $content) :
echo '<li>'.$content->status.'</li>';
echo '<p>'.$content->status_image.'</p>';
endforeach;
endif;
// echo '<pre>'; print_r($this->data['labels_message']); exit;
}
and then my model
public function get_all_content($id,$start,$content_per_page)
{
$query=$this->db->select('*')
->from('post_status')
->where('user_id',$id)
->limit($start,$content_per_page)
->get();
//echo "<pre>";
//print_r($query);
//var_dump($query);
$result = $query->result();
//echo "<pre>";
//print_r($result);
return $result;
}
how to show the data according to the database
let me add a image for database
I'm working on a CMS and the main core of the theming is with bootstrap. My issue arises with Ajax. I have my login module and it works fine to login and run the ajax, but the issue that is my dropdown menu does not work when I include the ajax libraries.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://www.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
Those are the libraries I'm including to run ajax, and my ajax code
plus the form that I'm using
<form name="panel_login" id="panel_login" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="process" id="process" value="panel_login">
<p><label for "username">Username</label>
<input type="text" id="username" name="username" class="text"></p>
<p><label for "password">Password</label>
<input type="password" id="password" name="password" class="text"></p>
<p>
<p id="error"></p>
<input type="submit" id="submit_login" class="button" value="Login"></p>
</form>
<script>
$(function() {
$('#submit_login').click(function(event) {
$.ajax({
type: $("#panel_login").attr("method"),
url: $("#panel_login").attr('action'),
data: $("#panel_login").serialize(),
success: function(data){
if(data == "0" ) {
$("#error").html("Incorrect Username or Password");
}
else {
location.reload();
}
}
});
event.preventDefault();
});
});
</script>
The process is thrown within a case switch which works fine, the only issue at this point is the broken dropdown menu.
The Dropdown Menu Code: (nav.dropdown.php)
<li class="dropdown">
<?php echo $this->dtitle; ?> <b class="caret"></b>
<ul class="dropdown-menu">
<?php $perms = $this->perms; ?>
<?php self::GetChildren($perms); ?>
</ul>
Which is included through a PHP function file
class DViews {
protected $db;
public $tprefix;
public $theme;
public function __construct() {
$this->db = new DDB();
$this->tprefix = TPREFIX;
$this->theme = theme_p;
}
public function LoadNavigation($perm, $menu) {
switch($perm) {
case "all";
self::AllNavigation($perm, $menu);
break;
case "user";
self::AllNavigation($perm, $menu);
break;
case "guest";
self::AllNavigation($perm, $menu);
break;
}
}
public function AllNavigation($perm, $menu) {
$query = <<<SQL
SELECT id,title,content,menuid,identifier
FROM {$this->tprefix}pages
WHERE active = :true
AND visibility = :all
AND menuid = :menu
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
':true' => 1,
':all' => $perm,
':menu' => $menu,
));
foreach($resource as $row)
{
$this->perms = $perm;
$this->id = $row['id'];
$this->title = $row['title'];
$this->identifier = $row['identifier'];
self::CheckParent($perm);
}
}
public function CheckParent($perm) {
$query = <<<SQL
SELECT parent
FROM {$this->tprefix}pages
WHERE parent = :id
AND active = :1
AND visibility = :perms
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
':id' => $this->id,
':1' => 1,
':perms' => $perm,
));
if(PRETTYURLS == true) {
$this->dlink = $this->identifier;
}
else {
$this->dlink = "?id=".$this->identifier."";
}
$this->dtitle = $this->title;
if($resource->rowCount() > 0 ) {
include($this->theme.'/'.ACTIVETHEME.'/nav.dropdown.php');
}
else {
include($this->theme.'/'.ACTIVETHEME.'/nav.single.php');
}
}
public function GetChildren($perm) {
$query = <<<SQL
SELECT id,title,content,menuid,identifier
FROM {$this->tprefix}pages
WHERE active = :true
AND visibility = :all
AND parent = :parent
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
':true' => 1,
':all' => $perm,
':parent' => $this->id,
));
foreach($resource as $row)
{
$this->title = $row['title'];
$this->dtitle = $this->title;
$this->identifier = $row['identifier'];
if(PRETTYURLS == true) {
$this->dlink = $this->identifier;
}
else {
$this->dlink = "?id=".$this->identifier."";
}
include($this->theme.'/'.ACTIVETHEME.'/nav.single.php');
}
}
Tried Adding
var $j = jQuery.noConflict();
$j(function() {
$j('#submit_logout').click(function(event) {
$j.ajax({
type: $("#panel_logout").attr("method"),
url: $("#panel_logout").attr('action'),
data: $("#panel_logout").serialize(),
success: function(data){
location.reload();
}
});
event.preventDefault(); // Prevent the form from submitting via the browser.
});
});
to no avail.
Not sure why it worked, but I stumbled into a resolution on the millions of bootstrap forums that it seems are out there.
Linking to the external
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
Instead of local seems to have resolved the issue between Jquery and Bootstrap conflicts
I m using codeigniter and would like to grab some user info with ajax. This is what I have but it s not working
In the view I have a defined variable:
<script type="text/javascript">
var end_user = "<? echo $user_id; ?>";
</script>
<div id="tabs6"></div>
js file:
function get_experience()
{
$.post(base_url + "index.php/home/get_experience", { user : end_user }, function(data) {
if (data.status == 'ok')
{
$("div#tabs6").html(data);
}
else
{ //nothing }
}, "json");
}
get_experience();
controller:
public function get_experience()
{
$this->load->model('experience_model');
$end_user = $this->input->post('user');
$one_exp = $this->experience_model->one_exp($end_user);
if ($one_exp->num_rows() > 0)
{
$one_exp_html = '<ul>';
foreach($one_exp->result() as $exp)
{
$one_exp_html .= '<li>';
$one_exp_html .= $exp->experience;
$one_exp_html .= '</li>';
}
$one_exp_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $one_exp_html);
return json_encode($result);
exit();
}
else
{
$result = array('status' => 'ok', 'content' => 'nothing here');
return json_encode($result);
exit();
}
}
model:
function one_exp($end_user)
{
$query_str = "SELECT experience FROM exp WHERE user_id = ?";
$query = $this->db->query($query_str, $end_user);
}
You need to add return $query to your one_exp method.
EDIT
You're setting user_id in your view, but then using end_user in your javascript function get_experience().
Also, since it's json you'll need to change the html fill to
$("div#tabs6").html(data.content);
For more debugging add an alert to your callback (right before if (data.status == 'ok') add alert(data);)
You've got to echo the result out I think, not return it.
I am not sure but problem occurs in end_user value in js.Try this oneView File:
<script type="text/javascript">
var end_user = "<? echo $user_id; ?>";
get_experience(end_user);
</script>
<div id="tabs6"></div>
The js file:
function get_experience(foo)
{
$.post(base_url + "index.php/home/get_experience", { user : foo }, function(data) {
if (data.status == 'ok')
{
$("div#tabs6").html(data);
}
else
{ //nothing }
}, "json");
}