I have a heroku website with ruby, but my issue is with one page in particular. The issue with that page is javascript. The page also has ajax on it. Here is my page:
<!DOCTYPE html>
<html>
<head>
<script>
var refreshDelay = 5000000;
function createRequestObject() {
var ro;
if(navigator.appName == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq() {
var newParent = document.getElementById('2');
var oldParent = document.getElementById('target');
while (document.getElementById('target').childNodes.length > 0) {
newParent.appendChild(document.getElementById('target').childNodes[0]);
}
http.open('post', '/chatContent?n=<%=#name%>');
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
var newParent = document.getElementById('2');
var oldParent = document.getElementById('target');
while (document.getElementById('target').childNodes.length > 0) {
newParent.appendChild(document.getElementById('target').childNodes[0]);
}
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('target').innerHTML = response;
setTimeout(sndReq(), refreshDelay);
}
}
setTimeout(sndReq(), refreshDelay);
</script>
<script>
scrollDown = function() {
document.body.scrollTop = document.body.scrollHeight;
}
</script>
</head>
<body onload='scrollDown()'>
<div id='2'>
</div>
<div id='target'>
<%=#chat%> <!-- #chat is a variable from my ruby file -->
</div>
<form action="/addChat?n=<%=#name%>" method='post'>
<input name='nchat' type='text' autofill='no' style='width:100%;height:10em;vertical-align:top'>
<input type='submit'>
</form>
<a href='/home'>Go home!</a>
</body>
</html>
When I load the page, it gives me this error in the console regarding line 24:
Uncaught TypeError: Cannot read property 'childNodes' of null
But when I enter into the console document.getElementById('target').childNodes.length it gives me however many nodes there are (it changes dynamically). What is going on??
Any extra things you want to see to answer this question I will try to promptly post. Just ask!
You are calling setTimeout(sndReq(), refreshDelay); which will execute sndReq() immediately because of the way you pass the function to setTimeout.
Since your sndReq() is in your head, the HTML will not have fully loaded yet so you are receiving the selector error because the element doesn't exist (yet).
You can change setTimeout(sndReq(), refreshDelay); to setTimeout(sndReq, refreshDelay); to pass the function reference to setTimeout so sndReq() doesn't fire immediately.
Ref: setTimeout
Related
I have a situation where I have two different sites, siteA.com and siteB.com, which need to share a common piece of information when a visitor navigates from siteA to siteB. I don't have access to the server-side code or navigation links from siteA, only limitied customizations and javascript. In order to share the information I have built a new page that is fully under my control at siteC.com, and then added this page as an iframe to both siteA and siteB. I am using the postMessage method to get and set the cookie from within the iframe which is working fine from each site, however I actually end up with two different cookies, one for each siteA and siteB even though the cookie belongs to siteC because it was set by the page in the iframe, confirmed through F12 debugger. I would have expected to have a single cookie and both sites could share the same cookie via the iframe, am I missing something here, should this be possible or is there another way to do this?
This is the code for my page at siteC that gets loaded into the iframe
<!DOCTYPE html>
<html>
<head>
<title>iframe source</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
var ck = document.cookie;
var expDate = new Date();
expDate.setFullYear(expDate.getFullYear() + 20)
$("#auditlog").append("iframe loaded<br/>");
if (ck) {
$("#auditlog").append("cookie exists<br/>");
} else {
$("#auditlog").append("cookie not set<br/>");
}
// Assign handler to message event
if (window.addEventListener) {
window.addEventListener('message', messageHandler, false);
} else if (window.attachEvent) { // ie8
window.attachEvent('onmessage', messageHandler);
}
})
function messageHandler(e) {
var msg = {};
var response;
// Check origin
if (e.origin === 'http://siteA' || e.origin === 'http://siteB') {
// Retrieve data sent in postMessage
msg = JSON.parse(e.data);
if (msg.action == "getCookie") {
response = getCookie();
} else if (msg.action == "setCookie") {
setCookie(msg.payload);
response = "cookie set";
} else {
response = "action not supported";
}
// Send reply to source of message
e.source.postMessage(response, e.origin);
}
}
function setCookie(cookieVal) {
var expDate = new Date();
expDate.setFullYear(expDate.getFullYear() + 20)
document.cookie = cookieVal + "; expires=" + expDate.toUTCString();
}
function getCookie() {
return document.cookie;
}
</script>
</head>
<body>
<div id="auditlog"></div>
<div id="cookieinfo"></div>
</body>
</html>
And this is code for my pages at siteA and siteB, both are using this same code, this is a sample I set up in order to test the set and get cookie functions in the iframe
<!DOCTYPE html>
<html>
<head>
<title>Main content page</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
// Assign handler to message event
if (window.addEventListener) {
window.addEventListener('message', messageHandler, false);
} else if (window.attachEvent) { // ie8
window.attachEvent('onmessage', messageHandler);
}
$("#btnGetIframeCookie").click(function () {
var postMsg = {
action:"getCookie"
}
// get reference to window inside the iframe
var wn = document.getElementById('cookieiframe').contentWindow;
// postMessage arguments: data to send, target origin
wn.postMessage(JSON.stringify(postMsg), 'http://siteC');
})
$("#btnSetIframeCookie").click(function () {
var cookieVal = $("#txtCookieValue").val();
var postMsg = {
action: "setCookie",
payload: cookieVal
}
var wn = document.getElementById('cookieiframe').contentWindow;
// postMessage arguments: data to send, target origin
wn.postMessage(JSON.stringify(postMsg), 'http://siteC');
})
})
function messageHandler(e) {
if (e.origin === 'http://siteC') {
$("#divMessages").append("response from iframe: <br/>" + e.data + "<br/>");
}
}
</script>
</head>
<body>
<div>
This is the iframe container
</div>
<div>
<input type="button" id="btnGetIframeCookie" value="Get iframe cookie" />
</div>
<div>
<input type="text" size="60" id="txtCookieValue" />
<input type="button" id="btnSetIframeCookie" value="Set iframe cookie" />
</div>
<iframe id="cookieiframe" src="http://siteC/iframe/index.html" style="width: 300px; height: 300px; border:1px solid black;"></iframe>
<div id="divMessages"></div>
</body>
</html>
Using this setup, if I set a cookie from siteA via the iframe with a value of "keyabc=value123" for example, I can then read that same cookie back, but when I go to siteB which has the same page in the iframe there, I don't have a cookie until I set one there, for example "keyabc=value456". Now if I look at my actual cookie files at C:\Users\aakoehle\AppData\Local\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\AC\#!001\MicrosoftEdge\Cookies I see two files, one with each of the values I set and both have the path of siteC. I also launched the F12 tools for each browser tab, each tab shows it's own cookie belonging to siteC.
-- UPDATE --
With the current version of my code posted here I am now only seeing the cookie issue in the Edge browser. Chrome and IE are sharing a single cookie between siteA and siteB as expected.
Here's an example for sharing data between cross origin sites, using localStorage and postMessage.
site1 : localhost:9091
<html>
<body>
<h1>site 1</h1>
<button id='postBtn'>Post message</button>
<br/>
<iframe id='commonSite' src='http://localhost:9093/commonSite.html' style='height:150px'></iframe>
<script>
(function () {
var commonSite = document.querySelector('#commonSite').contentWindow;
var postCounter = localStorage.getItem('postCounter');
postCounter = postCounter != null ? +postCounter : 1;
var commonOrigin = 'http://localhost:9093';
document.querySelector('#postBtn').onclick = function () {
commonSite.postMessage(postCounter++, commonOrigin);
localStorage.setItem('postCounter', postCounter);
console.log('site 1 posted');
}
})();
</script>
</body>
</html>
site2: localhost:9092
<html>
<body>
<h1>site 2</h1>
<button id='postBtn'>Post message</button>
<br/>
<iframe id='commonSite' src='http://localhost:9093/commonSite.html' style='height:150px'></iframe>
<script>
(function () {
var commonSite = document.querySelector('#commonSite').contentWindow;
var postCounter = localStorage.getItem('postCounter');
postCounter = postCounter != null ? +postCounter : 1;
var commonOrigin = 'http://localhost:9093';
document.querySelector('#postBtn').onclick = function () {
commonSite.postMessage(postCounter++, commonOrigin);
localStorage.setItem('postCounter', postCounter);
console.log('site 2 posted');
}
})();
</script>
</body>
</html>
commonSite: localhost:9093
<html>
<body>
<h3>Common site</h1>
<h4> Site 1 count: <span id='count1'></span></h3>
<h4> Site 2 count: <span id='count2'></span></h3>
<script>
(function () {
console.log('Adding message listener');
var origin1 = 'http://localhost:9091';
var origin2 = 'http://localhost:9092';
var count1 = document.querySelector('#count1');
var count2 = document.querySelector('#count2');
if(localStorage.getItem('count1')) {
count1.textContent = localStorage.getItem('count1');
}
if(localStorage.getItem('count2')) {
count2.textContent = localStorage.getItem('count2');
}
window.addEventListener('message', function (event) {
var origin = event.origin;
var data = event.data;
if(origin === origin1) {
localStorage.setItem('count1', data);
count1.textContent = localStorage.getItem('count1');
} else if(origin === origin2) {
localStorage.setItem('count2', data);
count2.textContent = localStorage.getItem('count2');
}
console.log('received (' + data + ') from ' + origin);
}, false);
})();
</script>
</body>
</html>
I have an extremely simple little JavaScript/Perl CGI example that I've used to get started with a larger project. When I run it as client.html and server.pl, it works flawlessly. However, when I change the client.html to client.tmpl, and call it from the same server.pl script using Template Toolkit, it can't seem to find jQuery functions.
I have even created a master.tmpl file, and used [% INCLUDE client.html %] inside it, and it fails. The browser console verifies that the path to jquery.js is correct, but it's like it fails to load it when it's inside a template.
The following is the HTML file that I'm essentially trying to turn into a .tmpl file (formatting messed up, first time here, sorry):
client.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js"></script>
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val()) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
});
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET", "http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text , true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text: <input type="text" id="user_text" name="user_text" onkeyup="myTimer()"/></div><br/>
<div>Server Resp.: <textarea id="server_response" name="server_response"> </textarea></div>
<br/>
</body>
</html>
The server.pl that works:
server.pl
$cgi = CGI->new;
$id = $cgi->param('user_text');
$result = uc($id);
print $cgi->header();
print $result;
The server.pl that doesn't work:
server.pl
$cgi = CGI->new;
$id = $cgi->param('user_text');
**returned from result calculation sub** $result = uc($id);
my $config = {
EVAL_PERL => 1,
POST_CHOMP => 1,
INTERPOLATE => 1,
INCLUDE_PATH => '/usr/lib/cgi-bin/ajax_example/:/var/www/html/ajax_example/',
};
print $cgi->header( -charset=>'utf-8' );
my $tt = Template->new($config);
$tt->process('client.tmpl', \$result);
}
Keep in mind, I am trying my best to summarize the code, but the Perl and JavaScript work just fine, unless it's being used through TT. The error is:
#user_text.keyup is not a function:
("#user_text").keyup(function(){
Same error I would get if I put in a bad path to jquery.js. The path is good though, without a doubt.
Thank you for any recommendations anyone can provide.
The immediate problem is that you have enabled the INTERPOLATE option, which interpolates Perl variables anywhere in the template. That makes the module attempt to replace $( by its value, and destroys the JavaScript syntax
It's a sloppy way of using templates anyway: you should pass all the values you need in the $vars hash, and extract them from there using [% variable %] template directives. The same applies to the EVAL_PERL option, as any complex data manipulation should ordinarily be in the code that calls process. Everything you need to do inside the template is available as a Template directive
Talking of the $vars hash, you should be getting Not a HASH reference errors, because you are passing to process a reference to the string variable $result instead of a hash containing that value. It's unclear how you want that value to be handled, but the only mention of id in your HTML is the id attribute of the <input> element at the bottom of the HTML, so I've put a directive in their to show you how it all works
Take a look at this code
CGI program
use strict;
use warnings 'all';
use CGI;
use Template;
my $cgi = CGI->new;
my $id = $cgi->param('user_text') // 'abc123';
my $result = uc $id;
print $cgi->header( -charset => 'utf-8' );
my $tt = Template->new( {
# INCLUDE_PATH => '/usr/lib/cgi-bin/ajax_example/:/var/www/html/ajax_example/',
POST_CHOMP => 1,
} );
$tt->process('client.html', { result => $result } );
I have modified your HTML file like this. I couldn't tell what you wanted to do with the value that the CGI code pulls from the user_text parameter, so I put it into a value attribute for the first input field
Template file
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js" />
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val() ) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
} );
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET",
"http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text,
true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text:
<input type="text" id="user_text" name="user_text" value="[% result %]" onkeyup="myTimer()"/>
</div>
<br/>
<div>Server Resp.:
<textarea id="server_response" name="server_response"/>
</div>
<br/>
</body>
</html>
And here's the resulting output from the CGI code. As you can see, the $("#user_text").keyup call remains intact, and the value from the CGI code—the result element passed in the $vars hash—has been substituted into the value attribute of the text input element
I hope this helps you to progress and get your application working
output
Content-Type: text/html; charset=utf-8
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<meta charset="UTF-8" />
<script src="http://domainname/ajax_example/jquery.js" />
<script type="text/javascript">
function myTimer() {
var typingTimer;
var doneTypingInterval = 2000;
$("#user_text").keyup( function() {
clearTimeout(typingTimer);
if ( $('#user_text' ).val() ) {
typingTimer = setTimeout(updateText, doneTypingInterval);
}
} );
function updateText() {
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if ( http.readyState == 4 && http.status == 200 ) {
var response = http.responseText;
document.getElementById('server_response').value = response;
}
};
http.open("GET",
"http://domainname/ajax_example/cgi-bin/server.pl?user_text=" + current_text,
true );
http.send();
}
}
</script>
</head>
<body>
<div>Input Text:
<input type="text" id="user_text" name="user_text" value="ABC123" onkeyup="myTimer()"/>
</div>
<br/>
<div>Server Resp.:
<textarea id="server_response" name="server_response"/>
</div>
<br/>
</body>
</html>
I am using java script after making an ajax call to display the data in a div with new JS content. Please refer to the code below:
//ajax call from a.jsp
var goUrl = "/testMethod/getTestMethod;
var httpRequest=null;
var refreshContent = "null";
httpRequest = XMLHTTPObject();
httpRequest.open("POST", goUrl, true);
httpRequest.onreadystatechange = function () {ajaxFunction(refreshThisDiv,httpRequest); } ;
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(null);
function ajaxFunction(refreshThisDiv,httpRequest){
var serversideValidation = true;
if (httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
results = httpRequest.responseText; // http.responseXML; which will lead to an XML based response, if we were to have some XML output from a server file
if(results != 'null') {
var test= document.getElementById(refreshThisdiv);
test.style.display = '' ;
test.innerHTML = results;
}
//Below is in b.jsp which is new content to display.
<div id="test">
</div>
<script>
var test = document.getElementById("test");
test.innerHTML ="HI";
</script>
Results are coing fine and redirecting to the b.jsp and displaying the html content. But tags are not working :(
I want to see Hi after ajax call is completed for that div. Please help me.
The ID is not #test, but test. #test is a selector that you'd use with jQuery, CSS or document.querySelector. document.getElementById requires, unsurprisingly, the ID. :)
getElementById() just needs the name of the ID. You incorrectly used CSS-ish syntax by passing #test where only test is needed.
Corrected new code:
<div id="test">
</div>
<script>
var test = document.getElementById("test");
test.innerHTML ="HI";
</script>
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
I've got a big database with over 30 000 records on my server. I make a request to the server giving me the first 100 records and showing them with Googlevisualisation table paging Api - 10 records per page.
In my code here I added an event listener for the "page" event and tested the page property of the event:if I have reached the last page, I make an AJAX call for more data (another 100 records)
The problem is that if I reach the last page it just loads it for a second and it makes immediately the Ajax call without waiting to click next and for that results it doesn't change my page property! how can i make this way - when I reach the last my next button to be enabled and when i click it only then to load the next 100 records
Here my code that I tried so far:
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table']});
</script>
<script>
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
} else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var intRpp=100;
var intPNum;
var glPNum;
var s;
var options = {'showRowNumber': true, 'pageSize':intPageSize };
var numberOfPages;
var intPageSize=10;
function loadXMLDoc(l)
{
intPNum=l;
s=l;
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
var xmlObj = xmlhttp.responseXML;
var textXML = xmlObj.documentElement.firstChild.firstChild.nodeValue;
if (window.DOMParser)
{
parser=new DOMParser();
var xmlDoc=parser.parseFromString(textXML,"text/xml");
}
else // Internet Explorer
{
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(textXML);
}
var rec = new Array();
rec[0]=['Стопански субект', 'Юрид.форма', 'Община', 'Име', 'Роля', 'Страна', 'NACE code', 'NACE text', 'Селище', 'пощ.код','Адрес', 'тел.', 'факс', 'Email', 'web', 'rid','id','activ'];
var rows = xmlDoc.getElementsByTagName("row");
rowsn = rows.length;
for (i=1;i<=rowsn;i++)
{
var cols=rows[i-1].getElementsByTagName("colunm");
colsn=cols.length;
rec[i] = new Array();
for (var j=0; j<colsn; j++)
{
rec[i][j] = cols[j].getAttribute("colvalue");
}
rec[i][j]='<input type="button" onClick="ajaxDBDelete('+rec[i][15]+');"/>';
}
tblTst = google.visualization.arrayToDataTable(rec);
options['page'] = 'event';
options['pageSize'] = intPageSize;
options['pagingSymbols'] = {prev: 'prev', next: 'next'};
options['pagingButtonsConfiguration'] = 'both';
options['allowHtml'] = 'true';
numberOfPages = intRpp/intPageSize;
visual = new google.visualization.Table(document.getElementById('table'));
google.visualization.events.addListener(visual, 'page', function (e){
options.startPage = e.page;
if (s>1)
{
glPNum = (numberOfPages * (s-1)) + (e.page+1);
document.getElementById('txbNumPage').value = glPNum;
options['pagingButtonsConfiguration']='both';
}
else
{
glPNum = e.page+1;
if (glPNum==1) options['pagingButtonsConfiguration']='next';
else options['pagingButtonsConfiguration']='both';
}
document.getElementById('txbNumPage').value = glPNum;
visual.draw(tblTst, options);
if (e.page == numberOfPages-1)
{
loadXMLDoc(s+1);
options.startPage = 0;
}
else
{
if((e.page==0)&&(s>1))
{
loadXMLDoc(s-1);
options.startPage=numberOfPages-1;
}
}
});
visual.draw(tblTst, options);
}
}
//alert (intRpp);
var url = "http://78.130.187.38:8080/axis2/services/bucat2/SelectFromDB?intRpp=" +intRpp + "&pageNum="+intPNum;
//alert (url);
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body onload= "loadXMLDoc(1);">
<br>
<br>
<div id="table"></div>
<br/>
<button type="button" name="btnFP" onClick="loadXMLDoc(1);">FIRST PAGE</button>
<input type="input" id="txbNumPage" value=1 />
<button type="button" name="btnLP" onClick="ajaxDBLast();">LAST PAGE</button>
<br>
<div id='proba'>
</div>
</body>
</html>
how can i make this way - when I reach the last my next button to be enabled and when i click it only then to load the next 100 records
Put your logic into a generic function
Set loadXMLDoc as a pointer to that function
Pass the page number as part of the query string to the AJAX URL
If the page number is the last one, then reassign loadXMLDoc to an empty function