So I'm trying to make a next/prev buttons using javascript, and have used a DynamicPage script to help test this. I've only changed the start of the URL variable in pagenumber.js however will essentially give the same message. I want to be able to click next/prev, which will then update the main body with another page of content via AJAX.
I checked the console and no errors are present, and opening the Network tab of the inspector shows the URL which I'm aiming to open is actually being loaded, however the container just displays
[object HTMLDivElement]
I've never properly used AJAX before so chances are I'm doing something wrong. If somebody could please point me in the right direction I'd be much appreciative!
Thanks.
My pagenumber.js is as follows:
var i = 0;
function loadPage(i) {
/* IMPORTANT: ENSURE var url equals the exact domain and location of inductions OR it will fail */
var url = "https://example.com/inductions/induction-page-" + i + ".html";
fetch(url).then(content => {
document.getElementById("guts").innerHTML = guts;
document.getElementById("display").innerHTML = i;
});
}
function incPage() {
i++;
if (i > 10) i = 1;
loadPage(i);
}
function decPage() {
i--;
if (i < 1) i = 10;
loadPage(i);
}
My main HTML is as follows:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
<script type='text/javascript' src='js/jquery.ba-hashchange.min.js'></script>
<script type='text/javascript' src='js/dynamicpage.js'></script>
<script type='text/javascript' src='js/pagenumber.js'></script>
<div id="container">
<div id="page-wrap">
<header>
<a id="decc"><input type="button" value="Previous" id="dec" onclick="decPage();"/></a>
<a id="incc"><input type="button" value="Next" id="inc" onclick="incPage();"/></a>
Page: <label id="display"></label>
</header>
<section id="main-content">
<div id="guts">
<h3>Initial Induction Page</h3>
<p>This is initial content on loading main HTML doc. This content will change when hitting next/prev buttons.</p>
</div>
</section>
</div>
Also, the dynamicpage.js is as follows:
$(function() {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("nav").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
console.log(window.location.hash);
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#guts")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " #guts", function() {
$mainContent.fadeIn(200, function() {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
});
$("nav a").removeClass("current");
$("nav a[href="+newHash+"]").addClass("current");
});
});
};
});
$(window).trigger('hashchange');
});
fetch returns a Response object. This object tells you how the server responded and allows you to extract the data you received in multiple ways. Since you use innerHTML to set the newly downloaded data you'll need to use the text() method of the response. This will return a promise that when finished presents the result in a string. And you should use that result to set your innerHTML with on the guts element.
If the content returned from the response is a full HTML page and you need a part from it, use the DOMParser API, parse the string to HTML and use querySelector to select the element which you need to content from.
var i = 0;
var guts = document.getElementById("guts");
var display = document.getElementById("display");
function loadPage(i) {
/* IMPORTANT: ENSURE var url equals the exact domain and location of inductions OR it will fail */
let url = "https://example.com/inductions/induction-page-" + i + ".html";
fetch(url).then(response => {
if (response.status === 200) {
return response.text();
}
throw new Error(`Error occurred fetching ${url}. Status: ${response.status});
}).then(getGutsFromContent).then(content => {
guts.innerHTML = content;
display.textContent = i;
});
}
function getGutsFromContent(content) {
const parser = new DOMParser();
const doc = parser.parseFromString(content, 'text/html');
const guts = doc.querySelector('#guts');
if (guts !== null) {
return guts.innerHTML;
}
}
Related
My goal is to load data from the appropriate file into div sections when I select any option.
I need to load <div> in one file from another (inside iframe). I'm stuck on how to get value and store it in variable. Everything works fine if I assign to variables (template_1, template_2, template_3) any static data but I want to load it from another files (template_one.html, template_2.html and so on).
template_1 has load() method but I know that this is wrong. Instead I want a path to appropriate file div. Same with other variables
I found a similar solution here with function load but I'm not sure if this will work and how add this to my function.
Array objects are random so please don't worry about it
jQuery(document).ready(function($) {
var template_1 = $('#section_one').load('template_one.html', '.section_one')
var template_2 = "<div><h1>template2</h1></div>"
var template_3 = "<div><h1>template3</h1></div>"
var templates_array = [
[template_1, template_1, template_1, template_1, template_1],
[template_2, template_2, template_2, template_2, template_2],
[template_3, template_3, template_3, template_3, template_3],
]
function load(url, element) {
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
document.getElementById('id_template').onchange = function(event) {
let get_val = event.target.selectedOptions[0].getAttribute("value");
if (get_val) {
for (let i = 0; i < templates_array.length; i++) {
var iframe = document.getElementsByTagName('iframe')[i].contentWindow.document;
var iframe_content = iframe.querySelector('body');
iframe_content.innerHTML = templates_array[get_val - 1][i];
};
} else {
for (let i = 0; i < templates_array.length; i++) {
var iframe = document.getElementsByTagName('iframe')[i].contentWindow.document;
var iframe_content = iframe.querySelector('body');
iframe_content.innerHTML = '';
};
};
};
});
project tree
Jquery Code
$(document).ready(function(){
$(document).on('click', '#button_1', function() {
$('#div_1').load('one.html')
});
$(document).on('click', '#button_2', function() {
$('#div_2').load('two.html')
})
});
HTML Code
Button_1
<BR>
<BR>
Button_2
<BR>
<BR>
<div id="div_1"></div>
<div id="div_2"></div>
I hope this one help you.
In the iframe:
<textarea id="ta"></textarea>
<script>
$(document).ready(function(){
$(document).on('change', '#ta', function() {
parent.textAreaChanged(this.value);
});
});
</script>
In the parent:
<div id="display"></div>
<script>
function textAreaChanged(value){
$('#display').text(value);
}
</script>
OK,so I am trying to pull some data from an api. The problem that I have run into is that I am able to find out the information that I am looking for, but am having trouble getting that information out of the console and onto my main index.html page.
Here is my JS code
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
$.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
console.log(info);
});
});
});
Here is my html code
<div id="search">
<h1>API Test</h1>
<input type="search" id="search-keyword">
<button id="myBtn">Try it</button>
</div>
<div id="results"></div>
By doing this, I am able to get pretty much what I am looking for. However I cannot get the data from the console to the actual page.
I have tried appendChild
var bob = document.getElementById(results);
var content = document.createTextNode(info);
bob.appendChild(info);
I have tried innerHTML
var theDiv = document.getElementById(results);
theDiv.innerHTML += info;
..and I have tried .append()
$('#myBtn').click(function() {
$(results).append(info)
})
I'm out of ideas. I realize that I probably have a small problem somewhere else that I am not seeing that is probably the root of this. Much thanks to anyone who can help me with this issue.
"results" needs to be in quotes with regular javascript and for jquery you have already decalred the results variable.
var theDiv = document.getElementById("results");
theDiv.innerHTML += info;
$('#myBtn').click(function(){
results.append(info)
})
Also since you are declaring results outside of your document ready call you have to make sure you html comes before the javascript.
<script>
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
var resultedData = $.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
return info;
});
var resultDiv = document.getElementById("results");
resultDiv.innerHTML += resultedData;
});
});
</script>
I have a webpage where I put status of my webservice task. It looks like this:
<body>
<div id="size">
<c:out value="${size}"/>
</div>
<div id="isRunning">
<c:out value="${isRunning}"/>
</div>
<div id="intIsRunning">
<c:out value="${intIsRunning}"/>
</div>
<div id="status">
<c:out value="${status}"/>
</div>
</body>
after rendering I get this:
<body>
<div id="size">
100
</div>
<div id="isRunning">
false
</div>
<div id="intIsRunning">
0
</div>
<div id="status">
0
</div>
</body>
size is the size of a job and can be any int value. isRunning is true or false and intIsRunning is 1 or 0. status is percentage completion of the job.
I'd like to be able to get content of those ids and put them into js variables on my other web page however I'm not js aficionado myself.
For now I have this:
$(document).ready(function() {
$('.progress .bar').progressbar();
var fetch = setInterval(loadStatus, 500);
var isRunning;
function loadStatus() {
$.get('/status #intIsRunning', function (data) {
console.log(data);
console.log("!");
console.log("--->("+$(data).index("#status")+")");
});
isRunning = 0;
console.log(">>" + isRunning);
// console.log($('.progress .bar').prop(['data-transitiongoal']));
// $('.progress .bar').prop(['data-transitiongoal']).load('/status #status');
// $('.progress .bar [data-transitiongoal]').load('/status #status');
// $('.bar').attr('data-transitiongoal', i.toString());
// console.log("progress: "+progress);
if (isRunning == 0) {
clearInterval(fetch);
}
}
});
This script should query my status page for aforementioned values and put status into my progress bar as long as running is true. If running is false this script should stop but right now I can't extract those variables. Could anyone provide help?
EDIT:
I got it to work that way:
<script type = text/javascript>
$(document).ready(function () {
$('.progress .bar').progressbar();
var fetch = setInterval(loadStatus, 500);
var isRunning;
var status;
function loadStatus() {
$.get('/status', function (data) {
var remoteContent = $(data);
isRunning = parseInt($(remoteContent[11]).html());
status = parseInt($(remoteContent[13]).html());
if (isRunning == 0) {
status = 100;
clearInterval(fetch);
$("#progBar").hide();
$("#buttonDiv").hide();
$("#succesMessage").show();
//location.reload();
}
$('.progress .bar').attr("data-transitiongoal", status.toString()).progressbar();
console.log("isRunning: " + isRunning + " status: " + status + "%");
});
}}
);
</script>
I'll check posted answer later this week.
What if you try something like this:
$(document).ready(function() {
var fetch = setInterval(loadStatus, 500);
$('.progress .bar').progressbar();
function loadStatus() {
$.get('/status', function (data) {
var $data = $(data), //turn ajax response (string) into JQuery collection
isRunning = $data.find('#isRunning').text(),
intIsRunning = $data.find('#isRunning').text(),
size = $data.find('#isRunning').text(),
status = $data.find('#isRunning').text();
//Do something with the variables
if (isRunning == 0) {
clearInterval(fetch);
}
});
}
});
Note that the variables will all be strings. You can cast to a number using status = parseInt(status, 10) or to boolean using isRunning = (isRunning != 'false'), for example. Note though that with javascript's implicit type conversions this is often not necessary.
For example:
<script>
$(document).ready( function() {
alert( $(this).getBelowElementToThisScript('form').id );
});
</script>
<form id="IamTheNext"></form>
<form id="Iamnot"></form>
This code should show this message: IamTheNext
In addition, the solution needs to work with this example too:
<script src="getbelowelement.js"></script>
<form id="IamTheNext"></form>
<form id="Iamnot"></form>
Thanks
Try this:
var form = $('script[src="getbelowelement.js"]').next();
But I would suggest using the forms id:
var form = $('#IamTheNext');
You could also try giving the script tag an id.
This kind of approach is dangerous; script should never depend that much on where it is in the page.
That said, the following works in Firefox and Chrome and should work in the major browsers (use at your own risk).
See it in action at jsBin. Both <script> ... and <script src="..."> approaches are shown in the same page.
$(document).ready( function () {
invocationsOfThis = (typeof invocationsOfThis == 'number') ? invocationsOfThis + 1 : 1;
var scriptTags = document.getElementsByTagName ('script');
var thisScriptTag = null;
//--- Search scripts for scripts of this type.
for (var foundCnt = 0, J = 0, L = scriptTags.length; J < L; ++J)
{
/*--- Since the script can be either inline or included, search
both the script text and the script src link for our unique
identifier.
*/
var thisTag = scriptTags[J];
var scriptCode = thisTag.innerText || thisTag.textContent;
var scriptSrc = thisTag.src;
//--- IMPORTANT, change pastebin.com to the filename that you use.
if (/invocationsOfThis/i.test (scriptCode) || /pastebin.com/i.test (scriptSrc))
{
//--- Found a copy of this script; is it the right one, based on invocation cnt?
foundCnt++;
if (foundCnt == invocationsOfThis) {
thisScriptTag = thisTag;
break;
}
}
}
if (thisScriptTag) {
//--- Get the target node.
var nextForm = $(thisScriptTag).next ('form');
var nextFormId = nextForm.attr ('id');
//--- Act on the target node. Here we notify the user
nextForm.text ('This is form: "' + nextFormId + '".');
}
} );
I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)