I am using an 'infinite scroll' script that keeps sending requests to the database even when there are no more records. When that happens, it reloads the last set on the page. I would like for the function to stop running when it reaches the last record on the database. I'm new to JS so this is a bit difficult for me to troubleshoot, also, I'm not using jQuery. I am doing most of the work in the PHP script.
I've been reading a lot of posts in here about 'infinite scroll' and I am unable to get how other people check the limits in JS.
JavaScript
function loadPosts(){
var target = document.getElementById('PostsContainer');
var contentHeight = target.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if(y >= contentHeight){
var xhr = ajaxObj("POST", "loadContent.php");
xhr.onload = function(){
target.innerHTML += xhr.responseText;
}
xhr.send("action=loadMore");
}
}
window.onscroll = loadPosts;
PHP
$sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC LIMIT 2" //Original content on page
$totalPosts = 12; (query to DB)
$max = 1;
$current = 2; //Start on record after initial content
while($current < $totalPosts){
$sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC
LIMIT $current, $max";
$result = $db_link->query($sql);
$posts_list += ... //Collect the data from DB
$current++;
}
echo $posts_list;
No matter how many times I keep scrolling the new content keeps loading even after I run out of records in the DB. Output keeps repeating every single time I get to the bottom of the page. In this case I have 7 posts in the DB I start with 7, 6... then I keep getting posts 5-1.
So in this case what you can do,
just add one parameter in json, from php or server side which will tell, is data present or not, based on that, you can stop calling loadPosts function
so basically Algorithm be like,
...php
while($current < $totalPosts){
......................
......................
if($current >= $totalPosts)
{
$getNext = False;
}
else
{
$getNext = True;
}
}
...javasrcipt
function loadPosts(){
if(!getNext)
return false;
else
{
......................
......................
}
}
window.onscroll = loadPosts;
Hope this strategy will help you
Related
I am trying to get my progress bar to update with the actual PHP code when completed.
var url2 = '';
function progressBarSim(al) {
var bar = document.getElementById('progressBar');
var status = document.getElementById('status');
status.innerHTML = al+"%";
bar.value = al;
al++;
var elem = document.getElementById("progressBar");
elem.style.width = al + '%';
var sim = setTimeout("progressBarSim("+al+")",77);
if(al == 100){
status.innerHTML = "100%";
bar.value = 100;
clearTimeout(sim);
var finalMessage = document.getElementById('finalMessage');
finalMessage.innerHTML = "<?php include('hi.php'); ?>";
}
}
var amountLoaded = 0;
progressBarSim(amountLoaded);
The above code works when I don't include PHP code inside my hi.php file but if I include any form of actual PHP code inside the file it will just make my entire progress bar not work anymore. How can I make my progress bar load hi.php when it's reached 100%?
You cannot access files, located on server via client javascript.
Moreover, all php scripts are running on server side.
UPD:
{
In your case you can do these things:
1)Load content that you want to show with other page - it's fit, if loading content does not vary.
2)Load content dynamically, using AJAX
}
If you want to load content dynamically, you should read about ajax queries.
Im using Sahi OS to look for emails in mailtrap shared inbox.
I can navigate to the folder, search for an email containing a string, do whatever has to be done and logout.
The issue is the speed.. It takes about 1 second for each step in navigation, thats OK. As soon as Sahi gets to the Inbox, it takes about 1-2 minutes for each step in search procedure.
here is my .sah
// Mailtrap check
loginMailtrap($mailtrapId, $mailtrapPwd);
gotoSharedInboxes();
checkForSmsTicketNumber($ticketNumber);
logoutMailtrap();
// Functions
function loginMailtrap($id, $pwd){
_navigateTo($mailtrapUrl);
_setValue(_emailbox("/email/"), $id);
_setValue(_password("/password/"), $pwd);
_click(_submit("Log in"));
_assert(_isVisible(_heading2("/My Inboxes/")));
}
function gotoSharedInboxes();
_click(_span("/Shared Inboxes/"));
_click(_span("Shared Inbox Name"));
}
function checkForSmsTicketNumber($tn){
var $smsTn = $tn.substr(5)
_log($smsTn);
var $go = true;
var $counter = 0;
while ($go) {
var $elm = _span(0, _in(_listItem($counter, _in(_list("messages_list inbox-content nav-list")) ) ));
var $elmText = _getText($elm);
_log($elmText);
var $index = $elmText.indexOf($smsTn);
if($index == -1){
$go = true;
$counter++;
} else {
$go = false;
_click($elm);
_assert(_isVisible($elm));
}
}
}
function logoutMailtrap(){
_click(_div("/username/"));
_click(_link("/Logout/"));
}
The email that Im looking for is the first in the list.
Step _log($smsTn) takes 2 minutes to complete after _click(_span("Shared Inbox Name"));
then it takes about 2 minutes for _log($elmText);
then 2 minutes for _click($elm);
then 2 minutes for logoutMailtrap();
Any ideas is Sahi parses mailtrap so slowly? Something todo with websockets? I dont have that issue with other sites. Thanks!
I have a slickgrid screen (on regular Domino form) wherein user can select and update some documents. I needed to show a pop-up displaying status of every selected document so I created an XPage. In my XPage I am looping through selected documents array (json) and call an RPC method for every document. Code to call RPC method is in a button which is clicked on onClientLoad event of XPAGE. RPC is working fine because documents are being updated as desired. Earlier I had RPC return HTML code for row () which was being appended to HTML table. It works in Firefox but not in IE. Now I am trying to append rows using Dojo but that’s not working either.
Here is my Javascript code on button click.
var reassign = window.opener.document.getElementById("ResUsera").innerHTML;
var arr = new Array();
var grid = window.opener.gGrid;
var selRows = grid.getSelectedRows();
for (k=0;k<selRows.length;k++)
{
arr.push(grid.getDataItem(selRows[k]));
}
var tab = dojo.byId("view:_id1:resTable");
while (arr.length > 0)
{
var fldList = new Array();
var ukey;
var db;
var reqStatusArr = new Array();
var docType;
var docno;
ukey = arr[0].ukey;
db = arr[0].docdb;
docType = arr[0].doctypeonly;
docno = arr[0].docnum;
fldList.push(arr[0].fldIndex);
reqStatusArr.push(arr[0].reqstatusonly);
arr.splice(0,1)
for (i=0;i < arr.length && arr.length>0;i++)
{
if ((ukey == arr[i].ukey) && (db == arr[i].docdb))
{
fldList.push(arr[i].fldIndex);
reqStatusArr.push(arr[i].reqstatusonly);
arr.splice(i,1);
i--;
}
}
console.log(ukey+" - "+db+" - "+docno+" - "+docType);
var rmcall = faUpdate.updateAssignments(db,ukey,fldList,reassign);
rmcall.addCallback(function(response)
{
require(["dojo/html","dojo/dom","dojo/domReady!"],function(html,dom)
{
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
html.set(tbdy,
tbdy.innerHTML+"<tr>"+
"<td>"+docType+"</td>"+
"<td>"+docno+"</td>"+
"<td>"+reqStatusArr.join("</br>")+"</td>"+
"<td>"+response+"</td></tr>"
);
});
});
}
dojo.byId("view:_id1:resTable").style.display="inline";
dojo.byId("idLoad").style.display="none";
RPC Service Code
<xe:jsonRpcService
id="jsonRpcService2"
serviceName="faUpdate">
<xe:this.methods>
<xe:remoteMethod name="updateAssignments">
<xe:this.arguments>
<xe:remoteMethodArg
name="dbPth"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="uniquekey"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="fieldList"
type="list">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="reassignee"
type="string">
</xe:remoteMethodArg>
</xe:this.arguments>
<xe:this.script><![CDATA[print ("starting update assignments from future assignments page");
var db:NotesDatabase = null;
var vw:NotesView = null;
var doc:NotesDocument = null;
try{
db=session.getDatabase("",dbPth);
if (null!= db){
print(db.getFileName());
vw = db.getView("DocUniqueKey");
if (null!=vw){
print ("got the view");
doc = vw.getDocumentByKey(uniquekey);
if (null!=doc)
{
//check if the document is not locked
if (doc.getItemValueString("DocLockUser")=="")
{
print ("Got the document");
for (i=0;i<fieldList.length;i++)
{
print (fieldList[i]);
doc.replaceItemValue(fieldList[i],reassignee);
}
doc.save(true);
return "SUCCESS";
}
else
{
return "FAIL - document locked by "+session.createName(doc.getItemValueString("DocLockUser")).getCommon();
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 0";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 1";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 2";
}
}
catch(e){
print ("Exception occured --> "+ e.toString());
return "FAIL - Contact IT Deptt - Code: 3";
}
finally{
if (null!=doc){
doc.recycle();
vw.recycle();
db.recycle();
}
}]]></xe:this.script>
</xe:remoteMethod>
</xe:this.methods>
</xe:jsonRpcService>
Thanks in advance
I have resolved this issue. First, CSJS variables were not reliably set in callback function so I made RPC return the HTML string I wanted. Second was my mistake in CSJS. I was trying to fetch tbody from table using
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
where as it returns an array so it should have been
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName**("tbody")[0]**;
also I moved tbody above while loop. I can post entire code if anyone is interested!!
I have quite a script that adds items into a table. I need to pull information from a MySQL database based on the UPC that is passed through the JavaScript.
I tried: document.write("<?php echo '375'; ?>"); just to see if it would work, and once the script got to that line, the page refreshed and displayed a blank white page.
The full JavaScript is below:
//setup before functions
var field = document.getElementById("UPC");
var typingTimer; //timer identifier
var doneTypingInterval = 1000; //time in ms, 1 seconds
//on keyup, start the countdown
$('#UPC').keyup(function(){
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#UPC').keydown(function(){
clearTimeout(typingTimer);
});
function doneTyping () {
//user is "finished typing," do something
if (field.value.length != 0) {
document.getElementById("noScan").className="hidden";
document.getElementById("checkout").className="";
document.getElementById("void").className="";
var upc=document.getElementById("UPC").value;
var price = document.write("<?php echo '375'; ?>");
var weight = parseInt(document.getElementById("weight").value);
var table=document.getElementById("ScannedItems");
var total = weight * price;
var row=table.insertRow(-1);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
var cell4=row.insertCell(3);
var cell5=row.insertCell(4);
var cell6=row.insertCell(5);
cell1.innerHTML=upc;
cell2.innerHTML="Example Description";
cell3.innerHTML = "$" + price.toFixed(2);
cell4.innerHTML = weight + " lbs";
cell5.innerHTML = "$" + total.toFixed(2);
cell5.setAttribute('data-total', total); // caches the total into data
cell6.innerHTML="<a class='add'><span class='glyphicon glyphicon-plus' style='padding-right:15px;'></span></a><a class='delete'><span class='glyphicon glyphicon-minus'></span></a>";
field.value ='';
var total = cell5.getAttribute('data-total');
var salesTax = Math.round(((total / 100) * 8.25)*100)/100;
var totalAmount = (total*1) + (salesTax * 1);
document.getElementById('displaysubtotal').innerHTML="$" + (Math.floor(total * 100) / 100).toFixed(2);
document.getElementById('displaytax').innerHTML="$" + salesTax;
document.getElementById('displaytotal').innerHTML="$" + totalAmount;
}
}
// Duplicate a scanned item
var $table = $('#ScannedItems');
$('#ScannedItems').on('click', '.add', function () {
var $tr = $(this).closest('tr').clone();
$table.append($tr);
});
// Remove a line item
var $table = $('#ScannedItems');
$('#ScannedItems').on('click', '.delete', function () {
var $tr = $(this).closest('tr').remove();
});
I must figure out how to get information from my database for this project or it is going to fail.
Javascript executes on the client side, PHP executes on the server side. So PHP is done executing before JS starts.
So in order to fetch new data, you'll need to initiate a call to your server. You can do this by either refreshing the page with the results you need or by creating an AJAX call.
To make it more clear, take a closer look at the example you gave. View the source code in your browser. It will come out as document.write("375");. That's because PHP echo'ed the string '375' into your JS code on the server side before sending the page to the browser (which is where the JS code executes).
PHP can generate JS code, but JS cannot generate PHP code (in the usual sense).
PHP is executed on the server before serving generate HTML to a clients browser. Any PHP code inserted by the javascript on the client will not run.
If you want to have code inserted dynamically from PHP, you might investigate how to use AJAX calls to run a separate PHP server-side script and insert the returned content.
You can perfectly use php inside javascript, because php executes before javascript reachs the browser. So the browser receives the page with the php result executed which builds the javascript sentence... the browser doesnt know that the javascript sentence was writen by you or by the php server.
document.write("<?php echo '375'; ?>");
try changing it to...
document.write("<?php echo("375"); ?>");
the "" are first seen by php server so the above should work.
or just in case you can escape the "
I also have this piece of code fully functional:
frameDoc.document.write sentence
<?php
echo("frameDoc.document.write(\"");
require('secciones/seccion_head2.html');
echo("\");");
?>
frameDoc.document.write sentence
BUT!!! inside the required html you cant use more than one line!!!!
Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps