not able to load javascript code - javascript

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>

Related

Display loader while waiting for Ajax response, then fade out the loader and fade in the response no jQuery

I am using a regular XMLHttpRequest and I want to display a loading element while waiting for the response and then display the response with an animation.
I was able to do this with jQuery, but I have found no answers for vanilla JS.
Here is the relevant code.
<div id="loader"></div>
<div id="demo" class="animate-bottom">
ooo
</div>
<button type="button" onclick="loadDoc()">Get the AJAX data</button>
The Css is not necessary, the loader is set to opacity 0.3(to see what is happening) and the
The JS
var output = ''; // the variable to hold the parsed response
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// so far ok, the trouble starts here, setting the loader to opacity 1
document.getElementById("loader").style.opacity = 1;
var theResponse = this.responseText;
var parsedResponse = JSON.parse(theResponse);
// the looping through the data
for (i=0; i < parsedResponse.length; i++ ) {
output += '<li>' + parsedResponse[i].title +'</li>' + '<img src=' +
parsedResponse[i].thumbnailUrl + '/>' + '<span>' + parsedResponse[i].url
+ '</span>';
};
// here the response goes to the demo div.
document.getElementById("demo").innerHTML = output;
}
// these 2 lines do not work as desired
document.getElementById("loader").style.display = "none";
document.getElementById("demo").style.display = "block";
};
xhttp.open("GET", "https://jsonplaceholder.typicode.com/photos", true);
xhttp.send();
}
I know, this is an asynchronous request and the problem lies there.
What is happening now, the demo div is animated to the screen as soon the button is clicked and the loader is not displayed while the data is parsed.
I am using a large data set , the request and parsing take few seconds.
Is there a way to make this work, or do I have to wrap some of the code into a setTimeout?
The codepen is here, I apologize for the time it takes to load the data(5seconds for me).
https://codepen.io/damPop/pen/gQOVEe?editors=0010

Apply JS onto table, which is created after page is loaded

I have got an html page, where you can put text into a textarea, click a button and then it creates an html table.
Problem is, that i am using a JS file to make my table sortable, but this JS file is not applied to tables that are created after the page itself is created.
How can i call the JS file again after the button is clicked and the table created? Or is there any other way to apply the JS file to the new table?
My problem seems to be like this problem:
Apply jquery propieties on new element created after the page is loaded
But i can't use JQuery, is there any way without it?
Example for a created table:
<div id="artikelnr2">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="table.css">
<script src="java.js"></script>
<div class="datagrid"><table class="sortable">
<thead><tr><th>Nummer</th><th>Nummer</th><th>Bezeichnung</th><th>Bemerkungen</th></tr></thead>
<tbody>
<tr><td>897-251</td><td>00.702.07803.7</td><td>5G2</td><td>-</td></tr><tr><td>897-1051</td><td>00.702.0306.7</td><td>5G1</td><td>-</td></tr><tr><td>897-1651</td><td>00.702.0307.3</td><td>5G1U</td><td>-</td></tr><tr><td>897-341</td><td>00.702.0323.9</td><td>5G2.5</td><td>-</td></tr>
</tbody>
</table></div>
</div>
I am using sorttable.js from this page:
http://www.kryogenix.org/code/browser/sorttable/
JavaScript which is called after button is clicked (pastes the content of another page into an exisiting div container):
function getOutput(url) {
var file = selectedValue()+".csv";
var value = document.getElementById("artikelnr").value;
<!---Leerzeichen entfernen-->
value = myTrim(value);
var url = url || "verarbeitung.php?eingabe="+value+"&eingabe2="+file ;
getRequest(
url, // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('artikelnr2');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('artikelnr2');
container.innerHTML = responseText;
tempResult = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
So this is a suggestion as a major part of your code is not available.
In your existing code, where you create the new table, you need to add/run the following:
sorttable.makeSortable(newTableObject);
The newTableObject reference you either can get straight from your existing code or by calling document.getElementById(idOfTheTableIJustAdded) after your added the new table to the DOM.
Src: http://www.kryogenix.org/code/browser/sorttable/
Update after question edit:
In this script function you should be able to do like this
function drawOutput(responseText) {
var container = document.getElementById('artikelnr2');
container.innerHTML = responseText;
//tempResult = responseText;
var newTableObject = container.querySelector(".sortable");
sorttable.makeSortable(newTableObject);
}

Odd Contradictory Error

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

Ajax Request generates html with potential for subsequent Ajax requests. Secondary requests return [object mouseevent] as opposed to generated value

I have a page that is loaded via php. One of the elements in the page is a <li> that has an onclick event. E.g. <li onclick="dynamiccall('1');">blah</li>. After clicking the element an ajax call is issued and the html output is inserted into the page, the tag looks as follows <li onclick="getubilling('1');">blah</li>.
After clicking the generated element with the onclick function getubilling('1');, an ajax call is sent to a php script. The query parameter in the second function to getubilling is displayed as 1, but upon passing it to the ajax call, it shows up as [object mouseevent]. Why is this happening?
the dynamiccall() function is defined as follows in the ajax.js file included in the page:
function dynamiccall(uid){
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse10(xmlHttp.responseText);
console.log(uid);
var holder = uid;
document.getElementById('orgcinfo').innerHTML = '<ul id="b_action_lst2"><li onclick="getuprofile('+holder+')" name="uprofile">Account Settings</li><li onclick="getubilling('+holder+')" name="billing">Billing</li><li onclick="getuchpass('+holder+')" name="chpass">Change Password</li><li onclick="getuadduser('+holder+')" name="adduser">Add User</li></ul>';
var ullist = document.getElementById('b_action_lst2');
var links = ullist.getElementsByTagName('li');
for(var i=0;i<links.length;i++){
var link = links[i];
if(link.getAttribute('name')=="uprofile"){
link.onclick = getuprofile;
}
if(link.getAttribute('name')=="chpass"){
link.onclick = getuchpass;
}
if(link.getAttribute('name')=="billing"){
link.onclick = getubilling;
}
}
//dothis();
}
}
xmlHttp.open("GET", "ajax.php?&p=anotherreq&uid="+uid+"&n="+Math.random(), true);
xmlHttp.send(null);
}
function getubilling(uid){
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse10(xmlHttp.responseText);
console.log(uid);
var holder = uid;
document.getElementById('orgcinfo').innerHTML = '<ul id="b_action_lst2"><li onclick="getuprofile('+holder+')" name="uprofile">Account Settings</li><li onclick="getubilling('+holder+')" name="billing">Billing</li><li onclick="getuchpass('+holder+')" name="chpass">Change Password</li><li onclick="getuadduser('+holder+')" name="adduser">Add User</li></ul>';
var ullist = document.getElementById('b_action_lst2');
var links = ullist.getElementsByTagName('li');
for(var i=0;i<links.length;i++){
var link = links[i];
if(link.getAttribute('name')=="uprofile"){
link.onclick = getuprofile;
}
if(link.getAttribute('name')=="chpass"){
link.onclick = getuchpass;
}
if(link.getAttribute('name')=="billing"){
link.onclick = getubilling;
}
}
//dothis();
}
}
xmlHttp.open("GET", "ajax.php?&p=gubilling&uid="+uid+"&n="+Math.random(), true);
xmlHttp.send(null);
}
A request is issued to http://www.domain.com/ajax.php?&p=gubilling&uid=1&n=2212.32313
The problem is that the resulting UID variable when rendered in the browser results to [object mouseevent] as opposed to the literal value of 1.
I was following this example the only difference I can see is that the example doesn't provide for
passing a dynamic element to the dynamicEvent function where mine does.
What am I missing? Any advice is appreciated.
I suspect this will be the default param passed into the onclick handler, the event object.
Why don't you use addEventListener for a start, rather than inline?
How does this:
dynamiccall('uniqueid');
Know what uniqueid's value is? where does it get it from? In this case, it's taking the value of the event that occurred. My suggestion would be to change the tag to look like this:
<li onclick="dynamiccall(this);" uniqueid="1">blah</li>
then you can set dynamiccall to:
function getubilling(elem) {
var uid = $(elem).attr('uniqueid');
...

fetching xml data into a div via ajax and javascript

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

Categories

Resources