Identifying content loading in ajax div

I am currently utilizing the ajaxpage feature from the code offered by Dynamic Drive ().

My goal is to have the original page, which sent the ajax content request to the div, recognize when the div has finished loading.

Here are the methods I have experimented with:

  • After conducting extensive research, it seems that many suggest using jQuery for this functionality. However, I prefer not to incorporate jQuery into this project.
  • I attempted including scripts in the loaded content, but it was unsuccessful. This could be due to restrictions within this feature.
  • I also tried monitoring various states of the div, but so far, no changes have been detected.

Ultimately, what I require is a way to trigger a function on the main page once the div content has completed loading.

Answer №1

Adjust the ajaxpage function by including an additional parameter for a callback function and ensure to call your function within onreadystatechange. However, I strongly suggest utilizing jQuery instead.

UPDATE:

Here is the revised approach that I implemented: I introduced a new parameter named callback to your existing function ajaxpage. When the ajax event triggers onreadystatechange, if we receive a true value from loadpage, we execute the callback. To differentiate between different pages or content, I added the *page_request* and containerid arguments. You can now integrate this callback function with your ajaxpage function; in this instance, I utilized a function called myCallbackFunction.

I urge you to avoid this method as it may be considered outdated. There are more efficient ways and best practices available, especially if you are still in the learning phase.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Ajax Rotating Includes Script</title>
<script type="text/javascript">

/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname

    function ajaxpage(url, containerid, callback) {
        var page_request = false
        if (window.XMLHttpRequest) // if Mozilla, Safari etc
            page_request = new XMLHttpRequest()
        else if (window.ActiveXObject) { // if IE
            try {
                page_request = new ActiveXObject("Msxml2.XMLHTTP")
            } catch (e) {
                try {
                    page_request = new ActiveXObject("Microsoft.XMLHTTP")
                } catch (e) {}
            }
        } else
            return false
        page_request.onreadystatechange = function () {
            if (loadpage(page_request, containerid)) {
                if (callback)
                    callback(page_request, containerid);
            }
        }
        page_request.open('GET', url, true)
        page_request.send(null)
    }

    function loadpage(page_request, containerid) {
        if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)) {
            document.getElementById(containerid).innerHTML = page_request.responseText
            return true;
        }
        return false;
    }

    function loadobjs() {
        if (!document.getElementById)
            return
        for (i = 0; i < arguments.length; i++) {
            var file = arguments[i]
            var fileref = ""
            if (loadedobjects.indexOf(file) == -1) { //Check to see if this object has not already been added to page before proceeding
                if (file.indexOf(".js") != -1) { //If object is a js file
                    fileref = document.createElement('script')
                    fileref.setAttribute("type", "text/javascript");
                    fileref.setAttribute("src", file);
                } else if (file.indexOf(".css") != -1) { //If object is a css file
                    fileref = document.createElement("link")
                    fileref.setAttribute("rel", "stylesheet");
                    fileref.setAttribute("type", "text/css");
                    fileref.setAttribute("href", file);
                }
            }
            if (fileref != "") {
                document.getElementsByTagName("head").item(0).appendChild(fileref)
                loadedobjects += file + " " //Remember this object as being already added to page
            }
        }
    }

    function myCallbackFunction(page_request,containerid) {
        // Perform necessary actions here 
        console.log("page_request", page_request);
        console.log("container id", containerid);
    }

</script>

<style type="text/css">
#leftcolumn{
float:left;
width:150px;
height: 400px;
border: 3px solid black;
padding: 5px;
padding-left: 8px;

}

#leftcolumn a{
padding: 3px 1px;
display: block;
width: 100%;
text-decoration: none;
font-weight: bold;
border-bottom: 1px solid gray;
}

#leftcolumn a:hover{
background-color: #FFFF80;
}

#rightcolumn{
float:left;
width:550px;
min-height: 400px;
border: 3px solid black;
margin-left: 10px;
padding: 5px;
padding-bottom: 8px;
}

* html #rightcolumn{ /*IE only style*/
height: 400px;
}
</style>
</head>

<body>

<div id="leftcolumn">
<a href="javascript:ajaxpage('ajaxfiles/external.htm', 'rightcolumn', myCallbackFunction);">Porsche Page</a>
<a href="javascript:ajaxpage('ajaxfiles/external2.htm', 'rightcolumn', myCallbackFunction);">Ferrari Page</a>
<a href="javascript:ajaxpage('ajaxfiles/external3.htm', 'rightcolumn',myCallbackFunction);">Aston Martin Page</a>

<div style="margin-top: 2em">Load CSS & JS files</div>
<a href="javascript:loadobjs('ajaxfiles/style.css', 'ajaxfiles/tooltip.js');">Load "style.css" and "tooltip.js"</a>

</div>

<div id="rightcolumn"><h3>Choose a page to load.</h3></div>
<div style="clear: left; margin-bottom: 1em"></div>

</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

This phrase cannot be invoked

My code seems correct for functionality, but I am encountering an error in my component that I do not know how to resolve. Can someone please help me with this issue? This expression is not callable. Not all constituents of type 'string | ((sectionNa ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Solution for displaying table cells in IE 7 and lower using Javascript

Lately, the community has come up with some amazing tools to push early versions of IE beyond their intended capabilities. For example, using multi-column CSS selectors. However, I've been struggling to find a JavaScript that can be loaded conditional ...

Saving a pointer to "this" for usage in a named function callback through the prototype pattern in JavaScript

Having encountered difficulties obtaining a reference to a JavaScript object structured with the prototype pattern within a callback, specifically coming from a 3rd party component integrated into my object. The said 3rd party object connects to a message ...

Set the array back to its initial value of 1 using jQuery and

After making substantial edits to this question, I find myself in need of a reset button for the code. The current item needs to be reset back to 1 so that I can use it again, but the issue lies in the fact that only the current item is reset while the hig ...

perform asynchronous calls within a for loop in a synchronous manner

Having issues with managing asynchronous events in sails.js. Obtaining data from a JSONapi and attempting to insert it into the database sequentially within a for loop. The goal is to maintain the correct order of execution. For simplicity, consider the f ...

Real-time messaging system with php, javascript, and mysql integration for live updates

Hey everyone, I'm in the process of incorporating a Facebook-like messaging system into my web application. Unfortunately, I can't share the link at this time due to login restrictions. In order to achieve this, I have set up a conversation tabl ...

What causes a "UnhandledPromiseRejectionWarning" while using Puppeteer?

What causes the following warnings to appear, and how can I resolve them? Warnings: (node:26771) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Protocol error (Runtime.callFunctionOn): Target closed. (node:26771) ...

A SyntaxError was encountered because functions in strict mode code must be declared either at the top level or directly within another function

Hey there, I'm encountering a strange issue with my project. Everything runs smoothly when I run it in Developer mode using `grunt server`. However, when I try to run it in production mode with `grunt build`, I encounter an error: Uncaught SyntaxEr ...

I am puzzled as to why, whenever I send the chosen option from a dropdown to PHP via Ajax, it consistently returns the initial option instead

Check out this code snippet I wrote: <html> <head> <script> initialize = function(){ document.getElementById('generate').onclick = sendRequest("generator.php"); } ...

Issue with jQuery .on('change') function not functioning correctly following a row being duplicated

Within my input form, I have implemented an on-click function that triggers an ajax call to submit a table row to the database. Upon submission, the row is then duplicated so that the user can input more data if necessary. The issue I am currently facing r ...

Utilizing AngularJS for Converting Date Formats from JSON and HTML Elements

So I have this controller set up. function TestCtrl($scope) { var contentFromJson = 'Hi! this is <b>Bold</b> and <i>Italic</i>'; var dateFromJson = '/Date(1394526738123)/'; $scope.Date = dateFromJso ...

What might be causing my AJAX success callback function to not function as anticipated?

I've written this code for an ajax request, but I'm struggling to figure out why the code inside the success method isn't functioning properly. Even though the network tab in my Chrome browser shows a state of 200 OK. Here is the ajax code ...

Using the Flow type checker with React library results in complications

I'm fairly new to JavaScript and React, so I appreciate your patience! I've recently started a project using create-react-app with React version 16.12.0. I installed a library that seems to be utilizing Flow. When attempting to use this library ...

Is it possible to utilize the spread operator for combining arrays?

Consider two different arrays represented by variables a and b. The variable c represents the output as a single array, indicating that this method combines two or more arrays into one. let a=[a ,b]; let b=[c ,d]; c=[a,...b] The resulting array will be: ...

Step-by-step guide on generating a downloadable file in Vue

As a beginner in Vue, I am tasked with downloading a file but unsure of how to proceed. My attempt at the code resulted in the image opening on a new page instead. <a class = "btn btn-success btn-xs" href = "https://78.media.tumblr.com/tumb ...

Is there a way to retrieve the dates from last month using jQuery?

Currently, I am unable to select past dates with the provided code. How can I adjust it to allow for selecting dates from previous months? let firstDay = new Date(); $('#date_filter_startmonthly').datepicker({ startDate: firstDay, endDate: ...

Recursion using Node.js Promises

I'm facing some difficulties while iterating through my Promises and completing my parser code: let startFrom = 0, totalRecords = 10000, doneRecords = 0 const rows = 10 const parserRequests = function () { if (startFrom <= totalRecords) { ...

Managing asynchronous data using rxjs

I created a loginComponent that is responsible for receiving an email and password from the user, then making an HTTP request to retrieve the user data. My goal is to utilize this user data in other components through a service. Here is the login componen ...

"Issues with Angular ng-show Functionality on Internet Explorer Versions 7 and

I'm currently working on a feature where I need to show or hide two divs conditionally using ng-show based on the completion of an AJAX call. The layout for this includes: <div id="div1" ng-show="!loadingData"> <!--Some markup here--> ...