I have put up some code to make an ajax, php, mysql chat in real time...
this is my code:
-jQuery/Ajax
$(function(){
setInterval(function() {
$('#chMsgCont').load('./ajax/msg.php');
var div = $('#chMsgCont');
var o = div.offset().top;
div.scrollTop( o + 12302012 );
}
,1000);
});
"./ajax/msg.php"
<?php
include("../system/config.site.php");
$query = mysql_query("SELECT * FROM chat_msg ORDER BY timestamp ASC");
while($p = mysql_fetch_assoc($query)) {
$auth = mysql_fetch_assoc(mysql_query("SELECT * FROM chat_users WHERE id = '".$p['auth_id']."'"));
?>
<div class="chatMsg">
<p id="chatPMsg">
<span class="chatTime"><?php echo date("H:i", $p['timestamp']); ?></span>
<b><?php echo $auth['name']." ".$auth['surname']; ?></b><br />
<?php echo stripslashes($p['msg']); ?>
</p>
<p id="chatImg">
<img src="./images/thumb<?php echo $p['auth_id']; ?>.png" />
</p>
<div style="clear:both;"><!– –> </div>
</div>
<?php
}
?>
I haven't found any method for not loading every second the "msg.php" file... I thought: is it possible to load initially the messages and then with setIntervall check for new messages to append to #chMsgCont? I think it is possible, but i can't figure out how to code it :/, can anyone help me?
Yes it is possible to load all messages upon initial page load; then subsequently update the chat window with new messages (have you ever wondered how Gmail auto populates new mail into your Inbox without a page refresh? Lots of AJAX requests).
You're on the right track. Just make sure you have a column in your MySQL database that holds a "yes/no" value on whether its a new message or not. Then everytime a new message is fetched using ajax/msg.php, in addition to fetching and outputting the content, perform a SQL update to update the fetched data as well.
Once you have that working you can further optimize your chat application by creating a simplier MySQL SELECT statement that simply checks the count of "new" rows (SELECT COUNT(new_message) FROM messages). Then check the value returned and whether it's greater than 0 before attempting to append content. I would also check for empty return data in your JavaScript to prevent from unnecessarily manipulating DOM elements.
Related
I have a link in a php while loop
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
The pop up requires the product id to search the database but hash tag is client side. I tried to use javascript window.location.hash but the outcome was not very reliable.
Does anyone know a method preferably server side I could use to retain the active product id while I call the pop up, attain the product id, use it to query the database and output it in the pop up.
I have a session already started and tied to a different condition.
I tried to call the product id directly from the pop up but because of the loop I only get either the first or last in the array.
<?
while ($i < $num) {
$product_id=mysql_result($result,$i,"prod_id");
$title=mysql_result($result,$i,"lTitle");
//main page
echo "<b>" , $title;
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
?>
<!------pop up--------->
<script type="text/javascript">
function pop_up(){
document.getElementById('pop').style.display='block';
}
</script>
<div id="pop">
<p style='color:#6F0A0A; font-size:15px;'><? echo $product_id; ?></p>
</div>
<?
$i++;
}
?>
I'll try answering but to be honest the question is very vague and the code is a bit messy.
First off, you can simply send the product_id as a GET variable to the new popup and read it in PHP. Something like this will work:
echo "<a href = 'http://www.mydomain.com/popup.php?product_id=$product_id' onclick="window.open(this.href, 'popup_win',
'left=100,top=100,width=500,height=500,toolbar=1,resizable=0'); return false;" id = 'linker' >See more</a>";
On your popup.php file (the popup page) you will get the product_id with the PHP $_GET method:
$product_id = $_GET['product_id'];
and then do whatever MySQL query you want, now that you know $product_id.
I hope this helps, if that's not exactly what you meant please add more details so I can revise my answer.
Well, you could first load all this records first and place them into the popup content or, make an ajax request, open the popup, and when the request is done successfully place the values returned into the popup content. Better with JQuery
I'm using colorbox for my PM system. I added a trash-btn so users can delete their messages whenever they like. When the user opened his PM (colorbox) and clicks the trash-btn to delete a message, it does not delete it. While whenever I browse directly to a message and hit the button, it does work. So it only doenst work when colorbox has been opened.
Since I'm a new to this and dont know much of javascript, I would like it if anyone could help me out abit. Here's my EDITED code
read_message.php form (this opens in the colorbox)
echo '
<div class="inboxMessage">
<div class="inboxMessageImg NoNewMsg"></div>
<div class="inboxMessageHeader">
<a id="ajax" class="inboxMessageLink" onclick="showMessage('.$row['message_id'].')">'.$row['message_title'].'</a>
<p class="inboxMessageStatus Read">'.$inboxMessageStatus_Read.'</p>
</div>
<div class="inboxMessageDescription">'.$inboxMessageDescription.'</div>
<div class="inboxMessageActions">
<form method="post" action="message/delete_message.php">
<input type="hidden" value="'.$row['message_title'].'" name="message_title">
<input type="hidden" value="'.$row['message_id'].'" name="message_id">
<input type="submit" class="deleteMessageIcon" value="" name="deleteMessage">
</form>
</div>
</div>';
This is delete_message.php page
<?php
include '../../includes/db_connect.php';
sec_session_start();
//Delete bericht uit db
if (isset($_POST['deleteMessage'])) {
$msgID = $POST['message_id'];
$msgTitle = $POST['message_title'];
$deleteMessage = mysqli_query($mysqli,"DELETE FROM messages WHERE message_title = '$msgTitle' AND message_id = '$msgID'") OR die(mysql_error($mysqli));
if($deleteMessage) {
echo "Deleted";
}else{
echo "Error - Try again";
}
}
?>
If you need more information, please let me know so.
Thanks in advance!
PS - I know anyone is able to change the message id and title in the form so he's able to delete messages. First of all, the user needs to know the whole title of anyone elses message. Besides that, I'll create a random number which will be the message_id so its not easy to get/find the message id - IM WORKING ON IT. First, the delete function needs to work properly.
I think I saw your error:
if the query is returning and doing nothing is because the condition is Wrong. If you try the query in PHPMyAdmin the Query is OK, the only thing I can think is in this part:
$msgID = $POST['message_id'];
$msgTitle = $POST['message_title'];
it should be:
$msgID = $_POST['message_id'];
$msgTitle = $_POST['message_title'];
if it doesn't work make:
print_r("DELETE FROM messages WHERE message_title = '$msgTitle' AND message_id = '$msgID'");
and let us know the output
Say I had the following:
$stmt = $pdo->prepare("SELECT jobName, jobDesc FROM Jobs");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$jName = $row['jobName'];
$jDesc = $row['jobDesc'];
print '<span class="job">Headline:</span> ' . $jName . '<br />
<span class="job">Description:</span>
<p class="job">' . $jDesc . '</p>';
}
The HTML output would be (for testing purposes)
<span class="job">Headline:</span> test 1
<span class="job>Description:</span>
<p class="job">test 1 Description</p>
<span class="job">Headline:</span> test 2
<span class="job>Description:</span>
<p class="job">test 2 Description</p>
<span class="job">Headline:</span> test 3
<span class="job>Description:</span>
<p class="job">test 3 Description</p>
If I wanted to remove one of these entries from the page, but keep it in the DB, how would I accomplish this with PHP? I'd probably have to put a link or button on each entry to remove it, and I know I can't actually take it off the page permanently with jQuery unless I use something to save the DOM state.
Thank you
I'd suggest adding a flag to the row in the DB along the lines of SHOULD_DISPLAY, and then set the flag for rows you don't want displayed and filter them out in that query (or at display time if for some reason that makes more sense).
There are different ways to accomplish this.
You could create a RESTful controller in PHP to implement basic CRUD operations, and then use jquery to delete/update each html element from your DOM and your DB.
Or you could just add a flag field to your database table, for example called "deleted", that can be true or false and let your php script render the row if it was not previously marked as deleted.
How do I Limit some information displayed from the database and add a link eg "More" to enable read all information in a drop down using PHP. such as what is on facebook (Read more...). I am dealing with a lot of content and I dont want it all displayed at once.
Here is part of the code
echo "<p>".$row['Firstname']." ".$row['Lastname']."</p>";
echo "<p>".$row["Course"]." | ".$row["RegID"]."</p>";
echo "<p>".$row["Email"]."</p>";
echo "<p>"."Tel:".$row["Telephone"]."</p>";
echo "<p>".$row["info"]."</p>";
The code is running well only that I want to limit the information
echo "<p>".$row["info"]."</p>";
so that not all is displayed
Thanks
Use Jquery-ui click on "view source" and you'll see it's very simple really, just set the row that you want as the header (what's clicked to show the rest) and store the rest in a div below.
Split info into two strings, one intro, and the rest. Display only the intro to begin with. Insert a link that displays the rest when clicked.
$intro = substr($row['info'], 0, 200);
$rest = substr($row['info'], 200);
echo sprintf(
<<<HTML
<p>
<span class="intro">%s</span><span class="rest" class="display: none">%s</span>
Show more
</p>
HTML
, htmlentities($intro)
, htmlentities($rest)
);
displayRest is a Javascript-function that, given a link, finds the previous span with class rest, shows it and removes the link. I leave it as an exercise to implement this in a way that fits your project. You can go with native Javascript, or use a library such as jQuery, YUI, MooTools, Prototype etc.
if(isset($_POST['more']))
{
$query="select col1,col2,col3, ... ,colN from tableName ";
}
else
{
$query="select col1,col2,col3 from tableName ";
}
//HTML
<form method="post">
<input type="submit" name="more" value="More" />
</form>
//PHP
$records=mysql_query($query);
while($row=mysql_fetch_assoc($records))
{
//Display
}
The limit must be fixed on the SQL request.
// If you want to transmit limitation with a GET PARAMETER.
// You can also $_POST ur data.
$limitation = $_GET['limit'];
//..... And in your SQL REQUEST
$sql = "SELECT * FROM your_table LIMIT 0 , $limitation";
//And in the link....
echo 'Show only 10 Results'
?>
You can optimize that and add security precaution to prevent errors when $limitation receive empty or non numeric parameters.
<?php if(isset($_GET['limit']) && !empty($_GET['limit']) && !preg_match(EXPRESSION, $_GET['limit'])){
//YOU CAN DO THE LIMITATION WHITOUT SQL ERRORS
}
else{
//ERROR DIRECTIVE
}
?>
NOTE: This is a long question. I've explained all the 'basics' at the top and then there's some further (optional) information for if you need it.
Hi folks
Basically last night this started happening at about 9PM whilst I was trying to restructure my code to make it a bit nicer for the designer to add a few bits to. I tried to fix it until 2AM at which point I gave up. Came back to it this morning, still baffled.
I'll be honest with you, I'm a pretty bad Javascript developer. Since starting this project Javascript has been completely new to me and I've just learn as I went along. So please forgive me if my code structure is really bad (perhaps give a couple of pointers on how to improve it?).
So, to the problem: to reproduce it, visit http://furnace.howcode.com (it's far from complete). This problem is a little confusing but I'd really appreciate the help.
So in the second column you'll see three tabs
The 'Newest' tab is selected by default. Scroll to the bottom, and 3 further results should be dynamically fetched via Ajax.
Now click on the 'Top Rated' tab. You'll see all the results, but ordered by rating
Scroll to the bottom of 'Top Rated'. You'll see SIX results returned.
This is where it goes wrong. Only a further three should be returned (there are 18 entries in total). If you're observant you'll notice two 'blocks' of 3 returned.
The first 'block' is the second page of results from the 'Newest' tab. The second block is what I just want returned.
Did that make any sense? Never mind!
So basically I checked this out in Firebug. What happens is, from a 'Clean' page (first load, nothing done) it calls ONE POST request to http://furnace.howcode.com/code/loadmore .
But every time you load a new one of the tabs, it makes an ADDITIONAL POST request each time where there should normally only be ONE.
So, can you help me? I'd really appreciate it! At this point you could start independent investigation or read on for a little further (optional) information.
Thanks!
Jack
Further Info (may be irrelevant but here for reference):
It's almost like there's some Javascript code or something being left behind that duplicates it each time. I thought it might be this code that I use to detect when the browser is scrolled to the bottom:
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
So what I thought was that code was left behind, and so every time you scroll #col2 (which contains different data for each tab) it detected that and added it for #newest as well. So, I made each tab click give #col2 a dynamic class - either .newestcol, .featuredcol, or .topratedcol. And then I changed the var col=$('.newestcol');dynamically so it would only detect it individually for each tab (makin' any sense?!). But hey, that didn't do anything.
Another useful tidbit: here's the PHP for http://furnace.howcode.com/code/loadmore:
$kind = $this->input->post('kind');
if ($kind == 1){ // kind is 1 - newest
$start = $this->input->post('currentpage');
$data['query'] = "SELECT code.id AS codeid, code.title AS codetitle, code.summary AS codesummary, code.author AS codeauthor, code.rating AS rating, code.date,
code_tags.*,
tags.*,
users.firstname AS authorname,
users.id AS authorid,
GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup
FROM code, code_tags, tags, users
WHERE users.id = code.author AND code_tags.code_id = code.id AND tags.id = code_tags.tag_id
GROUP BY code_id
ORDER BY date DESC
LIMIT $start, 15 ";
$this->load->view('code/ajaxlist',$data);
} elseif ($kind == 2) { // kind is 2 - featured
So my jQuery code sends a variable 'kind'. If it's 1, it runs the query for Newest, etc. etc.
The PHP code for furnace.howcode.com/code/ajaxlist is:
<?php // Our query base
// SELECT * FROM code ORDER BY date DESC
$query = $this->db->query($query);
foreach($query->result() as $row) {
?>
<script type="text/javascript">
$('#title-<?php echo $row->codeid;?>').click(function() {
var form_data = {
id: <?php echo $row->codeid; ?>
};
$('#col3').fadeOut('slow', function() {
$.ajax({
url: "<?php echo site_url('code/viewajax');?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('#col3').html(msg);
$('#col3').fadeIn('fast');
}
});
});
});
</script>
<div class="result">
<div class="resulttext">
<div id="title-<?php echo $row->codeid; ?>" class="title">
<?php echo anchor('#',$row->codetitle); ?>
</div>
<div class="summary">
<?php echo $row->codesummary; ?>
</div>
<!-- Now insert the 5-star rating system -->
<?php include($_SERVER['DOCUMENT_ROOT']."/fivestars/5star.php");?>
<div class="bottom">
<div class="author">
Submitted by <?php echo anchor('auth/profile/'.$row->authorid,''.$row->authorname);?>
</div>
<?php
// Now we need to take the GROUP_CONCATted tags and split them using the magic of PHP into seperate tags
$tagarray = explode(", ", $row->taggroup);
foreach ($tagarray as $tag) {
?>
<div class="tagbutton" href="#">
<span><?php echo $tag; ?></span>
</div>
<?php } ?>
</div>
</div>
</div>
<?php }
echo " ";?>
<script type="text/javascript">
var newpage = <?php echo $this->input->post('currentpage') + 15;?>;
</script>
So that's everything in PHP. The rest you should be able to view with Firebug or by viewing the Source code. I've put all the Tab/clicking/Ajaxloading bits in the tags at the very bottom. There's a comment before it all kicks off.
Thanks so much for your help!
I think you're right to suspect this code block:
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
My take on this is that you keep adding additional event handlers (duplicates, essentially) each time you run this code. You need to remove (unbind) the existing event handlers with every tab click so that you can be sure that it's only firing once:
$('#col2').unbind();
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
Or some such thing. See http://api.jquery.com/unbind/
$('.featurecol'); , $('.topratedcol'); and $('.newestcol'); all refer to the same column and division (<div>). As such, whenever you switch pages, you need to unbind the old scroll before rebinding the new scroll handler. (Or else you'll be appending another scroll handler and getting multiple requests sent, like now)
You can do this by adding an unbind as follows:
var col = $('.newestcol');
col.unbind('scroll');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
You need to do this for all of the columns as they load (code/newest, code/toprated and code/featured).
It could also be
$('#col3').fadeOut('slow', function() {
as the ajax loads there... n number of times as it fades out it calls another ajax request.
not saying its the defenet answer but something looking into...