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

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);
}

Related

Manage bootstrap modal with javascript

Good evening guys,
I program a symfony website by using webpack encore bundle to manage js & css.
I used to work with jquery which is quite simple, but would like to evolve to pure javascript.
I try to translate the following code in javascript :
<html>
<button class="exercice-class" data-id="x">exercice button</button>
</html>
when an user click on the "exercice button", i want to get the value of data-id to generate an URL
<script>
$(function() {
$('.exercice-class').on("click", function(e) {
e.preventDefault();
let id = $(this).data("id");
let url = "../exercice-class/" + id + "/";
$.get(url, function(data){
$(".container-fluid").append(data);
$('#showModal').modal('show');
});
});
});
</script>
Then i get the content of the URL and add it to the modal window
What I want to do first is to open a modal window by using a variable as a parameter.
Second question, I would like to get data from a modal (using a form) and send them to a database. I read things about asynchronous request by it's not really clear for me, i'm looking for something close to ajax request.
Thank you in advance.!
Juuk
here is a small example, you can test it
var classbutton = document.querySelector('.exercice-class');
classbutton.addEventListener('click', (e) => {
e.preventDefault();
let id = element.getAttribute('id');
let url = "../exercice-class/" + id + "/";
let requete = new XMLHttpRequest();
requete.open('GET', url);
requete.send();
requete.onload = function() {
if (requete.readyState === XMLHttpRequest.DONE) {
if (requete.status === 200) {
let reponse = requete.response;
document.querySelector('.container-fluid').append(reponse);
document.querySelector('#showModal').showModal();
}
else {
}
}
}
});
Thanks for your response! i tried your code and work on it...
This is what i did :
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", url);
httpRequest.send();
httpRequest.onload = function (){
if (httpRequest.readyState === XMLHttpRequest.DONE){
if (httpRequest.status === 200){
let httpResponse = httpRequest.response;
console.log(httpResponse);
}
}
}
It seems that fetch is a newer way to work with data since vanilla.
I did the same thing we tried to do before and i succeeded to get data.
document.addEventListener('click', function (event) {
if (!event.target.closest('.exercice-class')){
return null;
}
else {
event.preventDefault();
let exercice = event.target.closest(".exercice-class");
let dataAttribute = exercice.getAttribute('data-id');
let url = "../exercice-class/" + dataAttribute + "/";
fetch(url)
.then(function (response) {
return response.text();
})
.then(function (data) {
console.log(data)
})
.catch(function (error) {
console.log(error);
});
}
});
In reality i get the same result with the two solutions.. the problem is that i get "data" i can't exploit...
Imagine i use the second example :
if i try to do :
.then(function (data) {
let exerciceData = data.getElementById("#adiv");
document.querySelector('container-fluid').append(exerciceData);
document.querySelector('showModal').show();
"exerciceData" can't be used.
Modal just don't open.
Thank for your help.

Unable to check for if a file exists and perform statement

I am very new to javascripting and html.
I have built a web page that is mostly used to load either txt or other html pages using tag.
But I am trying to create a validation statement to check if the source file exists and load the iframe or if it doesn't to display a message.
I have tried the below code, but it just doesn't work.
Can anyone please help me?
<script>
var url = checkfile('../folder/test.html');
if (url.exists()){
<iframe id = "allviewer" src = "../folder/test.html"> < /iframe>
} else {
< p > This file does not exist < /p>
}
</script>
You should already avoid adding the iframe in the script tag, if you want to check if the file exists you can use ajax but the ajax already allows you to see the content so the iframe is no longer really necessary
<script type="text/javascript">
function url_exists(url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest;
xhr.open("GET", url, false);
xhr.send();
if (xhr.status == 200) resolve(xhr);
else reject(xhr.status);
})
}
const file = '../folder/test.html';
url_exists(file).then(t => {
console.log(t.response); // show file content in the console
ouputNode.innerHTML = `<iframe id="allviewer" src="${file}"></iframe>`;
}).catch(e => {
// on error
});
</script>
<div id="ouputNode"></div>

Why doesn't this chrome extension work?

I want to collect the url (var name is 'url') of a webpage into a variable in a chrome extension, together with several user inputs in text inputs, and to send it to a remote php script for processing into an sql database. I am using AJAX to make the connection to the remote server. The popup.html contains a simple form for UI, and the popup.js collects the variables and makes the AJAX connection. If I use url = document.location.href I get the url of the popup.html, not the page url I want to process. I tried using chrome.tabs.query() to get the lastFocusedWindow url - the script is below. Nothing happens! It looks as though it should be straightforward to get lastFocusedWindow url, but it causes the script to fail. The manifest.json sets 'tabs', https://ajax.googleapis.com/, and the remote server ip (presently within the LAN) in permissions. The popup.html has UI for description, and some tags. (btw the response also doesn't work, but for the moment I don't mind!)
//declare variables to be used globally
var url;
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
// Change the value of the outputText field THIS PART IS NOT WORKING YET
function setOutput(){
if(httpObject.readyState == 4){
//document.getElementById('outputText').value = httpObject.responseText;
"Bookmark added to db" = httpObject.responseText; // does this work?
}
}
//put URL tab function here
chrome.tabs.query(
{"active": true, "lastFocusedWindow": true},
function (tabs)
{
var url = tabs[0].url; //may need to put 'var' in front of 'url'
}
);
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
//get url? THIS IS OUTSTANDING - url defined from chrome.tabs.query?
description = document.getElementById('description').value;
tag1 = document.getElementById('tag1').value;
tag2 = document.getElementById('tag2').value;
tag3 = document.getElementById('tag3').value;
tag4 = document.getElementById('tag4').value;
httpObject.open("GET", "http://192.168.1.90/working/ajax.php?url="+url+"&description="+description+"&tag1="+tag1+"&tag2="+tag2+"&tag3="+tag3+"&tag4="+tag4, true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput(); //THIS PART IS NOT WORKING
finalString = httpObject.responseText; //NOT WORKING
return finalString; //not working
} //close if
} //close doWork function
var httpObject = null;
var url = null;
var description = null;
var tag1 = null;
var tag2 = null;
var tag3 = null;
var tag4 = null;
// listens for button click on popup.html
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', doWork);
});
Having no responses I first used a bookmarklet instead. The bookmarklet passes the url and title to a php script, which enters them into a db before redirecting the user back to the page they were on.
javascript:(function(){location.href='http://[ipaddress]/bookmarklet.php?url='+encodeURIComponent(location.href)+'&description='+encodeURIComponent(document.title)})()
Then I found this code which works a treat.
var urlOutput = document.getElementById('bookmarkUrl');
var titleOutput = document.getElementById('bookmarkTitle');
if(chrome) {
chrome.tabs.query(
{active: true, currentWindow: true},
(arrayOfTabs) => { logCurrentTabData(arrayOfTabs) }
);
} else {
browser.tabs.query({active: true, currentWindow: true})
.then(logCurrentTabData)
}
const logCurrentTabData = (tabs) => {
currentTab = tabs[0];
urlOutput.value = currentTab.url;
titleOutput.value = currentTab.title;
}

not able to load javascript code

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>

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');
...

Categories

Resources