issues with onClick event not getting triggered on DOM - javascript

I've got an API that returns me {"html", "Css" and "JS"} that i'd ideally like to render on client side.
Issue:
Looks like something's failing for some reason and clicking on the button does not do anything. (I have accept button)
JavaScript:
function postAjax(success) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('GET', '/myaccount/profile/api/accept');
xhr.onreadystatechange = function() {
if (xhr.readyState > 3 && xhr.status == 200) {
success();
}
};
xhr.setRequestHeader('Accept', 'application/json', 'Content-Type', 'application/json');
xhr.send(null);
return xhr;
};
document.onreadystatechange = function() {
if (document.readyState == "interactive") {
// some logic
var cookieLanguage = document.getElementById("CookieContent_wrapper");
var cookieBanner = document.getElementById("CookieBanner");
var acceptAllButton = document.getElementById("acceptAllButton");
acceptAllButton.onclick = function() { // Does not get trigerred.
// Does not get trigerred.
// Do some logic.
};
}
};
However, acceptAllButton.onClick event is not triggerred.
This is my directive.js (angular)
populate() {
this.cookieBannerData = this.models.CookieData; // We are getting { "js", "html", "css"}
//CSS
$("head").prepend( this.cookieBannerData.css );
// HTML
let div = document.getElementById( 'cookie-banner-outerwrap' );
div.insertAdjacentHTML( 'beforeend', this.cookieBannerData.html );
//JS
$("head").append( this.cookieBannerData.js );
}
template.html
<div id="cookie-banner-outerwrap"></div>
When I click on the button, nothing happens. Is there anyway I can bind the onclick event with window so that I can get my

Related

Reload / insert script after inserting div via XMLHttpRequest

I would like to run a script that has event listeners on a feed of posts. When I add a new post to the feed I have a function that makes a fetch call to add the post to the server and then proceed to update the DOM asynchronously. While I'm updating the DOM I would like to refresh the feed div where all the post are. I'm using an update() function that makes an XMLHttpRequest and updates the div, but after the new post is updated to the DOM I lose the initial script that contains event listeners for the posts.
function post() {
content = document.querySelector('#exampleFormControlTextarea1').value
console.log(content)
fetch('/add', {
method: 'POST',
body: JSON.stringify({
content: content,
})
})
.then(response => response.json())
.then(result => {
// Print result
if (result.error) {
document.querySelector('#message').className = "alert alert-danger rounded width_1"
document.querySelector('#message').innerText = result.error
document.querySelector("#message").style.display = 'block';
} else {
document.querySelector("#message").style.display = 'block';
document.querySelector('#message').className = "alert alert-success rounded width_1"
document.querySelector('#message').innerText = result.message
setTimeout(function () {
document.querySelector('#message').style.display = "none"
}, 2500)
setTimeout(function () {
document.querySelector("#add").style.display = 'none';
}, 500)
update()
console.log(result);
}
});
return false;
}
function update() {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.status >= 200 && this.status < 400 && request.readyState == 4) {
// Success!
var resp = this.response;
let div = document.createElement('div')
div.innerHTML = resp
let content = div.querySelector('#jqpost').innerHTML
let post = document.createElement('div')
post.innerHTML = content
let feed = document.querySelector('#feed')
feed.insertAdjacentElement('beforebegin', post)
//console.log(script_text)
} else {
// We reached our target server, but it returned an error
// console.error(request.statusText);
}
};
request.open('GET', '/', true);
request.send();
}
How can I keep the event listeners script after I reload the feed?

Using AJAX to change div content - how do I display navigation as hash / anchor

I want to create a page that refreshes content within a div async alongside providing a user with an anchor to enable direct access to the content within the div. (e.g. www.website.co.uk/#page1)
I've managed to make it so that the content can be updated for 1 page, however, if I add multiple pages it stops working
Additionally - if I was to navigate to the URL website.co.uk/#page1 it wont display #page1.
Can anyone help?
This is my current code:
HTML :
<h5> Test</h5>
<h5> Test2</h5>
JS :
<script type="text/javascript">
var routes = {
'#page1' : '{{site.url}}/page1'
'#page2' : '{{site.url}}/page2'
};
var routeHandler = function( event ) {
var hash = window.location.hash,
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(hash)) routehandler();
});
</script>
You made some small js errors.
So here is you fixed code
html:
<h5> Test</h5>
<h5> Test2</h5>
<div id="div1"></div>
javascript:
//change these routs
var routes = {
'#page1': '/page1.html',
'#page2': '/page2.html'
};
var routeHandler = function() {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[window.location.hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(window.location.hash)) routeHandler();
});
You usually use a router-like object for this. Instead of the hyperlink you're using, set the href to the actual page hash Button Title. Then create an event listener for the hashchange on the window object where you will fetch the content.
And finally add a list of webpages you want to be able to navigate to, so you can translate '#page1' to the actual url.
The result is that you can use simple hrefs in your hyperlinks and the current page will be shown in the url bar at the top.
ps: add a check into the hashchange listener for routes that aren't listed, so you can still link to offsite pages as well.
pps: If you want to be able to directly navigate to a page, you'll need to add a manual check of the hash at document load.
// html mockup
Button Title
// js mockup
var routes = {
'#page1' : '{{site.url}}/webpage.html'
};
window.addEventListener('hashchange', function( event ) {
var hash = window.location.hash, // gives you '#page1'
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[hash], true);
xhttp.send();
});
Updated with a load listener:
// html mockup
Button Title
// js mockup
var routes = {
'#page1' : '{{site.url}}/webpage.html'
};
var routeHandler = function( event ) {
var hash = window.location.hash, // gives you '#page1'
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(hash)) routehandler();
});
since you have tagged the question with jquery, iassume you have jQuery available, in this case you could do something like:
$(window).on('hashchange', refreshContent);
function refreshContent() {
$.get(getBaseUrl() + location.hash, function(data) {
$('#div1').html(data);
});
}
But please be aware that there are a lot more sophisticated solutions out there
I given directly on onclick its working. It may help you.
<h5> Test</h5>
<h5> Test2</h5>
<div id="div1"></div>
<script type="text/javascript">
var routes = {
'#page1' : 'page1.html',
'#page2' : 'page2.html'
};
function test(page) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[page], true);
xhttp.send();
}
</script>
I used .html for pages for check. You use your own.

Javascript setTimeout and Chrome Workers, I don't get it

I have the following files: (inc.js is included in my html page)
inc.js
var field = new Worker('ajax.js');
field.addEventListener('message', function(e) {
var data = JSON.parse(e.data);
document.getElementById('fieldToUpdate').innerHTML = data[0];
}, false);
field.postMessage(0);
ajax.js
var xhr = new XMLHttpRequest();
function getData() {
xhr.open('get', 'field.php');
xhr.onreadystatechange = processData;
xhr.send(null);
}
function processData() {
if (xhr.readyState == 4) {
self.postMessage(xhr.responseText);
setTimeout(getData, 5000);
}
}
onmessage = function() {
setTimeout(getData, 5000);
}
My Problem is now, that this Script doesn't make one http request each 5 seconds but it starts as soon as one is finished.

AJAX function parameter is null?

i got a problem with JS:
On line 1 to 4 I take all "a"-Elements from the DOM and get their hrefs.
later I want to reload the URL via AJAX, but the href does not arrive correctly... Whats wrong?
$(document).ready(function(){
$('a').click(function(e){
ajaxReload($(this).attr('href'));
e.preventDefault();
});
});
function ajaxReload(href) {
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", href, true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState != 4) {
document.write('loading');
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('hello');
//alert('getting '+xmlhttp.status+' for '+href);
var pureHTML = xmlhttp.responseText;
var ajaxstart = pureHTML.indexOf('<!-- AJAX START -->');
var ajaxend = pureHTML.indexOf('<!-- AJAX END -->');
var ajaxContent = pureHTML.substring(ajaxstart, ajaxend);
var writeContent = document.getElementById('content');
writeContent.innerHTML = ajaxContent;
}
}
xmlhttp.send(null);
}
Sorry if I've misunderstood your code. I think that you simply need to (at least approximately) just remove code as commented below:
//$('a').click = function(href) {
var pureHTML = xmlhttp.responseText;
var ajaxstart = pureHTML.indexOf('<!-- AJAX START -->');
var ajaxend = pureHTML.indexOf('<!-- AJAX END -->');
var ajaxContent = pureHTML.substring(ajaxstart, ajaxend);
$("content").html(ajaxContent);
// ajaxReload(href); //this would cause a loop?
// return false;
//}
To answer your later question - you can change your event propagation handling to:
$(document).ready(function(){
$('a').click(function(e){
ajaxReload($(this).attr('href'));
e.preventDefault();
});
});
And for the further comments, maybe try changing your:
document.write('loading');
To:
$("content").html(xmlhttp.status); //so now you can see the loading status for testing

"Object doesn't support..." IE8 stops at declaring ordinary variable

I'm trying to make a form send its data through AJAX and cancel the event sans jQuery, just for learning native JavaScript, which can never be bad, I figured. Anyway, this code is returning the error:
"Object doesn't support this property or method"
in IE8 at the line where I declare variables s and r in the send() function. I figured the problem must actually be elsewhere? Code works in both Firefox and Chrome, returning no errors. Ideas?
// Function to serialize form
function serialize() {
var a = document.getElementsByTagName('input'), b = '';
for (i = 0; i < a.length; i++) {
b += a[i].name + '=' + a[i].value + '&';
}
return b.substring(0, b.length - 1);
}
// Function to execute when user submits form
function send(evt) {
// Prevent the page from reloading
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
// Declare DOM variables for quick access
var s = document.getElementsByClassName('skicka')[0], r = document.getElementById('return');
// Hides the submit button and return text
s.style.visibility = 'hidden';
r.style.visibility = 'hidden';
// Initialize and send data and request to login.php
var xhr = new XMLHttpRequest();
xhr.open('POST', 'login.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(serialize());
// Check for return value from login.php
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.responseText == true) {
// If response if true, reload page
window.location.reload(true);
} else {
// If response is false, reset form and show response
s.style.visibility = 'visible';
r.style.visibility = 'visible';
r.innerHTML = xhr.responseText;
}
}
};
return false;
}
// Declare event listeners
if (window.addEventListener) {
window.addEventListener('load', function() {
document.forms[0].addEventListener('submit', send, false);
}, false);
} else {
window.attachEvent('onload', function() {
document.forms[0].attachEvent('onsubmit', function() {
send(window.event);
});
});
}
IE8 does not support .getElementsByClassName(). See the Ultimate GetElementsByClassName for a pure JavaScript implementation that will work in IE.

Categories