I am currently using ajax to load all content from 'mysite/math/' into math.php. I want to render the loaded math content using katex.
Inside math.php, I include the Katex library from the CDN mentioned in the link above.
The HTML structure of math.php:
<body>
<div id='main'>
</body>
In the script tags within math.php, there is PHP code that retrieves a list of URLs from 'mysite/math/':
echo "var x = [];";
$dir = "./math/";
$a = scandir($dir);
foreach ($a as $x) {
if ($x === '.' or $x === '..') continue;
echo "x.push('mysite/math/" . $x . "');";
}
This creates an array, x, containing the locations of each file's content to be loaded into the webpage.
To load the content, multiple AJAX calls are made to the URLs in the x array using JavaScript:
// defining the ajaxing function
function myfunction(url, someFunction) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
someFunction(this, url);
}
};
xhr.open('GET', url, true);
xhr.send(null);
}
// defining the callback function
function callbackfunction(xhr, url) {
var name = url;
var div = document.createElement('div');
div.innerHTML = xhr.responseText;
div.className += name;
document.getElementById('main').appendChild(div);
}
// executing the ajax calls
for (var i = 0; i < x.length; i++) {
myfunction(x[i] + '?w=' + Math.random(), callbackfunction);
}
At this point, everything works smoothly.
The issue:
Within each HTML file in 'mysite/math/', there are span tags with the class='math' that hold the math content I intend to render. Despite observing these tags inside math.php, they do not render properly when accessed via ajax.
Furthermore, math.php includes JavaScript utilizing the katex function katex.render():
var math = document.getElementsByClassName('math');
for (var i = 0; i < math.length; i++) {
katex.render(math[i].innerHTML, math[i]);
}
The current usage of katex only functions correctly if the content is not being fetched via ajax.
Note: Many similar questions have been answered with jQuery solutions, but I specifically require a JavaScript solution.