I have a small problem, I want to a live search that returns me a POST_TITLE and a POST_ID. the title is for the people to see but my main reason is that I want the POST_ID to work with it.
Can someone help me, I posted the code below...
<script>
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
}
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
var str = escape(document.getElementById('txtSearch').value);
searchReq.open("GET", '/wp-content/themes/twentyten/livesearch.php?search=' + str, true);
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);
}
}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
var sx = document.getElementById('restaurantid')
sx.innerHTML = '';
var ss = document.getElementById('search_suggest')
ss.innerHTML = '';
var str = searchReq.responseText.split("\n");
for(i=0; i < str.length - 1; i++) {
//Build our element string. This is cleaner using the DOM, but
//IE doesn't support dynamically added attributes.
var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
suggest += 'onmouseout="javascript:suggestOut(this);" ';
suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
suggest += 'class="suggest_link">' + str[i] + '</div>';
ss.innerHTML += suggest;
ss
}
}
}
//Mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
document.getElementById('txtSearch').value = value;
document.getElementById('restaurantid').value = value;
document.getElementById('search_suggest').innerHTML = '';
}
</script>
<form id="frmSearch" action="">
<input type="text" id="restaurantid" name="restaurantid" style="display: none;" />
<input type="text" id="txtSearch" name="txtSearch" alt="Search Criteria" onkeyup="searchSuggest();" autocomplete="off" />
<input type="submit" id="cmdSearch" name="cmdSearch" value="Search" alt="Run Search" />
<div id="search_suggest"></div>
</form>
</code>
livesearch.php - THE AJAX PAGE
<code>
<?php
$con = mysql_connect('x', 'x', 'x);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xx", $con);
if (isset($_GET['search']) && $_GET['search'] != '') {
//Add slashes to any quotes to avoid SQL problems.
$search = addslashes($_GET['search']);
//Get every page title for the site.
$suggest_query = mysql_query('SELECT * FROM `mrr_posts` WHERE `post_title` LIKE \'%'.$search.'%\' AND `post_status` LIKE \'publish\' LIMIT 0, 30') or trigger_error("Query: $suggest_query\n<br />MySQL Error: " .mysql_error());
while ($suggest = mysql_fetch_array($suggest_query, MYSQL_ASSOC)) {
//while($suggest = db_fetch_array($suggest_query)) {
//Return each page title seperated by a newline.
echo $suggest['post_title'] . "\n";
}
}
mysql_close($con);
?>
I noticed in the discussion above you're returning JSON now, and parsing it from the client side. And I noticed you tagged your question with jQuery, so I guess you're using that. This isn't an answer to your question, but here are some tips for javascript coding with jQuery that will help simplify your code a ton.
instead of doing your ajax calls using the XMLHttpRequest object directly, just use $.get(url, successFunction)
instead of using getElementById('some-id'), use $('#some-id'), then to do things like empty out the inner html, you can do $('#some-id').html(''). Using the jQuery element instead of HTMLElement, you can also manipulate the DOM in a cross-browser compatible way: http://api.jquery.com/category/manipulation/
instead of building your javascript into your HTML (all those onmouseover and onmouseout handlers), use $('div.suggest_link') to select all divs on the page that have a class of "suggest_link". Then, attach a live event handler which will work on dynamically generated html, like this: $('div.suggest_link').live('mouseover', handleMouseOverForSuggestLink). You can read more about this on jQuery's page: http://api.jquery.com/live/
All these suggestions will work in modern browsers, and will help cut down a lot of code. Good luck!
You should return data from server in JSON (or XML, but JSON is easier), and then parse it in Javascript. Show titles to user, id keep for yourself.
In general xajax might simplify things quite much. Have a look at my answer here:
how to assign a javascript variable to a smarty variable
Related
Can anybody help me with this problem please. I've been researching for days and I can't make the php echoed array containing html code to be formatted for the responseText of javascript.
I've tried to format the echoed array with json_encode($array) but doesn't work.
I've tried responseText.split(" ") and then used a for loop to extract the html code inside the array but I can't either.
I know the javascript code is working because I manually inserted html code like this:
i.e
responseText = '<p><img src="img/moon.png">here is your image</p>'
This works perfect.But when php spits out the array all I see on the screen with the code you see below is the Array word.
I know my php code is also working because I tested it before sending the text using POST method.
Your help is appreciated.
My ajax to php
<script>
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form- urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
</script>
<script>
function gotext(){
var mm = document.getElementById("todotext").value;
var isTr=false;
var ajaxfile = ajaxObj("POST", "env.php");
ajaxfile.onreadystatechange = function() {
if(ajaxReturn(ajaxfile) == true) {
document.getElementById("outputimgs").innerHTML = ajaxfile.responseText;
}
}
ajaxfile.send("todotext="+mm);
}
$(document).ready(function(){
$('form[name=uturn]').on('submit', function(e) {
e.preventDefault();
gotext();
$('html, body').animate({
scrollTop: $("#first").offset().top
}, 1000);
return false;
});
});
</script>
This is the html form
<form name="uturn" action="process.php" method="post">
<textarea id="todotext" name="text" placeholder="type or paste words here"></textarea><br/>
<input type="submit" id="arefbut" class="button scrolly" value="Convert"/>
</form>
<!-- First -->
<section id="first" class="main">
<div class="container">
<h2>Done !!</h2>
<p id="outputimgs">end</p>
</div>
This is the dynamic construction of html in php
if(isset($_POST['todotext'])) {
$chunk = $_POST['todotext'];
$commentArray = explode(" ",$chunk);
.
.
.
$commentArray[$i]='<p class="pos"><img src="imgs/blank.png" width="40" height="40"><br>
'.$commentArray[$i].'</p>';
$together = implode(" ",$commentArray);
echo $together;
All,
I found where the problem was. Like I said the only thing coming to the web page was the word Array; that output was coming from the str_replace, which was later changed into $commentArray[$i] in the middle of the html code to be echoed out to responseText. I had to add this for loop to fix it. I don't know off a better way to do it. The rest of the html was ignored and to fix this I added the html_entity_decode function.
The final code looks like below.
All is working perfect now.
See here the for loop added
if(isset($_POST['todotext'])) {
$chunk = $_POST['todotext'];
$text = explode(" ",$chunk);
$delimiter = array(" ",",",".","'","\"","|","\\","/",";",":","?",">","<","~","_","-","=","+","*","!","#","#","$","%","^","&","(",")");
$replace = str_replace($delimiter, $delimiter[0], $text);
for ($i=0; $i<count($replace); $i++)
{
if ($replace[$i]!==' ')
{
$newreplace .= $replace[$i].' ';
}
}
$newreplace = preg_replace('/\s+/', ' ', $newreplace );
$commentArray= explode($delimiter[0], $newreplace);
Here is the new treatment to $commentArray
for ( $i=0; $i<$counter;$i++)
{
$commentArray[$i]= html_entity_decode('<p class="pos"><img src="imgs/black.png" width="40" height="40"><br>'.$commentArray[$i].'</p>');
}
$together = implode(" ",$commentArray);
echo $together;
}
So i'm working on a javascript/php chatbox. Everything works except for it updating the contents of my div (this works once, but after that it doesn't keep updating it when a new message has been put into the database). Here is my code:
Javascript part:
<script language=javascript type='text/javascript'>
setInterval(function () {
var arrayOfObjects = <?print_r(getChatArray());?>;
var chat = "";
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
chat += "["+object.date+"]"+object.op+": " + object.msg + "</br>";
}
$('#chat').html(chat);
}, 10);
</script>
Php part:
<?php
function getChatArray() {
$result = mysql_query("SELECT * FROM shouts ORDER BY id DESC");
$to_encode = array();
$count = mysql_num_rows($result);
$size = 0;
if($count > 0) {
while($row = mysql_fetch_assoc($result)) {
$to_encode[$size]['id'] = $row['id'];
$to_encode[$size]['msg'] = $row['msg'];
$to_encode[$size]['op'] = $row['op'];
$to_encode[$size]['date'] = $row['date'];
$size += 1;
}
} else {
return "None";
}
return json_encode($to_encode);
}
?>
Any ideas as to why it isn't continually updating it?
Thanks.
Because every 10 milliseconds your JS is parsing the original chat room contents, you're not fetching any new contents. You'll need to implement an ajax call, and I'd highly recommend changing that setInterval to a recursive setTimeout with a more realistic delay of say 500ms so you don't kill the client.
Instead of this:
setInterval(function() {
var arrayOfObjects = <?print_r(getChatArray());?>;
...
You would use something like this:
(function updateChat(){
var arrayOfObjects,
chat,
max,
_object,
i = 0;
$.ajax({
url : '/getChatArray.php', // php echoes the json
success: function(arrayOfObjects){
for (max = arrayOfObjects.length; i < max; i++) {
_object = arrayOfObjects[i];
chat += "["+_object.date+"]"+_object.op+": " + _object.msg + "</br>";
}
$('#chat').html(chat);
setTimeout(updateChat, 500);
}
});
}());
Obviously you would populate that ajax handler to your needs, add some more params like dataType, etc, and some error handling.
Your database contents will only be output to the page on initial navigation to it.
This code:
var arrayOfObjects = <?print_r(getChatArray());?>;
Will only output the contents of getChatArray()'s return when PHP renders the page. So the script can only see one state of that functions return at the time of rendering.
You need to use AJAX to retrieve the content from your database asynchronously.
I suggest you:
Create a PHP script which outputs your data in JSON format
Use jQuery, specifically the getJSON function to retrieve that script's output
Do what you want to do with that data.
I have the following ajax.js, which I must use:
var xmlRequest = null;
function ajax(url, parametersArray, callbackFunction, fcnVars) {
if (xmlRequest != null) {
if (xmlRequest.readyState == 2 || xmlRequest.readyState == 3) {
xmlRequest.abort();
xmlRequest = null;
}
}
if (parametersArray == null)
parameters = "";
else
parameters = formatParameters(parametersArray);
if (window.XMLHttpRequest)
xmlRequest = new XMLHttpRequest();
else
xmlRequest = new ActiveXObject("MSXML2.XMLHTTP.3.0");
xmlRequest.open("POST", url, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
if (xmlRequest.responseText) {
callbackFunction(xmlRequest.responseText, fcnVars);
}
}
}
xmlRequest.setRequestHeader("Content-length", parameters.length);
xmlRequest.setRequestHeader("Connection", "close");
xmlRequest.send(parameters);
}
function formatParameters(parameters) {
var i = 0;
var param = "";
for (index in parameters) {
if (i==0) {
param += index+"="+urlencode(parameters[index]);
} else {
param += "&"+index+"="+urlencode(parameters[index]);
}
i++;
}
return param;
}
function urlencode(clearString) {
clearString = encodeURI(clearString);
clearString = clearString.replace('&', '%26');
return clearString;
}
and I have the following mysql table:
CREATE TABLE `dictionary` (
`word` varchar(64) NOT NULL,
PRIMARY KEY (`word`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
on the end, here is my search page:
<div id = "search">
<form id="searchform" method="post">
Search for Word:
</select>
<input type="text" id="search_term" name="search_term" />
<input type="submit" id="cmdSearch" value="Search" />
</form>
<div id="search_results"></div>
</div>
Now, I have to create a php function which will return an array with the words found in the table, using the above ajax.js
Results should be shown within the search_results div using ajax.
Of course, I will need a javascript code as well.
Anyone can help me to start to build this? I have done similar things with jquery,but now I must use this script, and I have no other way to do it.
Goal is to display the results in the php page without refresh.
Any help will be deeply appreciated
Update:
Here is my php code:
<?php
// add encoding here
header("Content-Type: text/html; charset=iso-8859-7");
// include the database connection here
include 'config.php';
include 'openDb.php';
function findWords(){
// sanitaze the user input
$term = strip_tags(substr($_POST['search_term'],0, 100));
$term = mysql_escape_string($term);
// query the database. one fileld only, so nothing to optimize here
$sql = "SELECT word FROM dictionary WHERE word like '%$term%'";
$result = mysql_query($sql);
// set the string variable
$string = '';
// if resulta are found then populate the string variable
if (mysql_num_rows($result) > 0){
while($row = mysql_fetch_object($result)){
// display the results here in bold and add a new line or break after each result
$string[] = "<b>".$row->user_name."</b><br/>\n";
}
} else {
// if no results are found, inform the visitors...
$string[] = "No matches!";
}
// output the string
return $string[];
Here is the javascript:
<script type='text/javascript'>
ajax("findWord.php", {id:search_term}, function(result,params) {
alert("result for ID: "+params.id+"\n\n"+result);
}, {id:search_term});
</script>
You will have to rely on the ajax function which lets you access whatever it loaded in the callback function:
callbackFunction(xmlRequest.responseText, fcnVars);
And ajax explains how it should be called itself:
ajax(url, parametersArray, callbackFunction, fcnVars)
Even though parametersArray should actually be an object ({index:value, i1:v2,...}) rather than an array ([val1, val2,...]). fcnVars can be an object containing anything that you want passed on to the callback function.
This should work:
ajax("add_page.php", {id:535}, function(result,params) {
alert("result for ID: "+params.id+"\n\n"+result);
}, {id:535});
I have a Ajax PHP MySQL live search that basically pulls out food items from a MySQL database and presents them in a drop-down list, as users enter they search term, one item per line, just like searching in Google.
What I need is a way to allow users to click on a particular result item, and for that to open up, just below the item clicked, a box with a few radio buttons listing options with various amounts of that particular food item. The user would then be able to select an amount option and click submit to save their selection.
I know PHP and MySQL and HTML quite well, but JS is a bit of a challenge, so I'd appreciate if you could be detailed in your answer.
Below are some code snippets with what I have at this point:
The HTML search form:
<input type="text" size="30" name="food_name" id="q" value="" onkeyup="sendRequest(this.value);" autocomplete="off"/>
The AJAX code on same page w/ search form:
function createRequestObject() {
var req;
if(window.XMLHttpRequest){
// Firefox, Safari, Opera...
req = new XMLHttpRequest();
} else if(window.ActiveXObject) {
// Internet Explorer 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Problem creating the XMLHttpRequest object');
}
return req;
}
// Make the XMLHttpRequest object
var http = createRequestObject();
function sendRequest(q) {
// Open PHP script for requests
http.open('get', 'checkfoods.php?q='+q);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4 && http.status == 200){
// Text returned FROM the PHP script
var response = http.responseText;
if(response) {
// UPDATE ajaxTest content
document.getElementById("searchResults").innerHTML = response;
}
}
}
The PHP script that looks into a table called FOOD_DES into MySQL and brings back the results populating the drop-down list of foods:
include 'my-food-dtabase.php';
$searchQry = isset($_GET['q']) ? mysql_real_escape_string($_GET['q']) : false;
if ($searchQry) {
$searchString = $_GET['q'];
$sql = mysql_query("SELECT NDB_No, FdGrp_Cd, Long_Desc FROM FOOD_DES WHERE Long_Desc LIKE '%".$_GET['q']."%' ORDER BY Long_Desc ASC");
if($searchString != NULL) {
while($row = mysql_fetch_assoc($sql)) {
echo "<span id=foodlist>".$row['Long_Desc']."<br /></span>";
}
}
if(mysql_num_rows($sql) == 0) {
echo "<span class=medium_white>Food item not found. Try a different name or keyword.</span>";
}
}
This isn't necessarily a complete answer but a pointer in the right direction.
You will save yourself a tonne of time and effort by using jQuery over pure JavaScript. It will also reduce your step 2 down to a few lines of code as it comes with its own Ajax API. Here's a tutorial on its Ajax system - much easier!
jQuery UI is a great extension to jQuery which helps you to build user interfaces, part of this is the dialog widget. I think the 'Modal form' dialog example is very similar to what you are trying to achieve when you click the 'create new user' button. Click 'View Source' to see how they did it.
Also from what I can see in step 3 you aren't sanitising your query, $_GET['q'] is being thrown right into your query string. You should replace this with $searchQry which you already defined a few lines above.
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
});
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Description
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}
http://koding.info/2013/07/ajax-search-box-php-mysql-jquery/
I have implemented a demo Live search application which uses Wordpress database.
Take a look.
it may help you.
i am trying to code endless pagination and having a trouble
$(document).ready(function(){
function lastPostFunc()
{
$('div#lastPostsLoader').html('<div class="load"><div class="label"><font color="black"><b>Loading more...</b></font></div></div>');
$.post("cr/sc/scr.php?lastID="+$(".comment:last").attr("id"),
function(data){
if (data != "") {
$(".comment:last").after(data);
}
$('div#lastPostsLoader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
lastPostFunc();
}
});
});
here goes my php
$result = mysql_query('SELECT * FROM xyz ORDER BY sy DESC LIMIT 15');
while($row = mysql_fetch_object($result)) {
$i++;
echo "<div class='comment' id='" . $i. "'>";
}
and other page to grab data
$pg = $_GET['lastID'];
$i=$pg;
$result = mysql_query('SELECT * FROM xyz ORDER BY sy DESC LIMIT '.$pg.',15');
while($row = mysql_fetch_object($result)) {
$i++;
echo "<div class='comment' id='" . $i . "'>";
}
Im getting a problem in getting value of comment:last
i get 15 value of comment:last after 1st time event loads
i get 15 value of comment:last after 2nd time event loads
which is problem im expecting 30
and on 3rd time event occures it gives 30
and same proccess again 30,30,40,40,50,50
instead of 30,40,50,60,70,80
i tried jquery live(), and i used $_GET cause im fetching from URL
Check to see if you are loading the function somewhere else, because the function loads and stops on mine, and the only way I can get it to mimic what you say is if I load the function again on page load, which will create two calls at the same time. Causing 1-15 and 1-15 and the last number off the page. Then on scroll it loads the function as it's supposed to and keeps on loading, just as you tell it too.
Plus, make sure you are checking that get (or even if you use a post) that goes directly into your database. That is asking for an injection.
EDIT: You should probably load full page (and past) first if you have the data. Then load the scroll function, which won't load if the page isn't full. Which is why it stopped for me.
EDIT2: This is the code I was using in case you want to see. I made a mock database, so I didn't have to match a db to test.
<?php
$scroller = 30;
if ( isset($_GET['hold']) && $_GET['hold'] == '1' ) {
$i = isset($_GET['lastID'])?(int)$_GET['lastID']:0;
$j = $i + $scroller;
//sleep(10);
while( $i < $j ) { // mimic a mysql call and spit it out.
++$i;
echo "<div class='comment' id='${i}'>${i}</div>";
}
exit;
}
?>
<html>
<head>
<script src="jquery-1.7.min.js" type="text/javascript"></script>
<script type="text/javascript">
// I was doing something else with this, but stripped out the code
var scroller = <?php echo $scroller;?>;
$(document).ready(function(){
function lastPostFunc()
{
// this assumes there are already comments on the page, so put a dummy comment
var last = $(".comment:last").attr("id");
$('div#lastPostsLoader').html('<div class="load"><div class="label"><font color="black"><b>Loading more...</b></font></div></div>');
$.post("<?php echo $_SERVER['PHP_SELF']; ?>?hold=1&lastID="+last,
function(data){
if ( data != "" ) {
$(".comment:last").after(data);
}
$('div#lastPostsLoader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
lastPostFunc();
}
});
lastPostFunc();
});
</script>
</head>
<body>
<div class="comment_container">
<div class="comment" id="0"></div>
<div id="lastPostsLoader"></div>
</div>
</body>
</html>