WP.org acceptable iframe alternative

Question edited:

I'm working on an alternative to iframes because WP.org balks at them and tends to reject plugins that have them (I know this from experience) So, here's the code I have to try to replace an iframe:

add_action('wp_ajax_myAction', array($this, 'myAction_ajax_handler'));
public function myAction_ajax_handler() {
   echo time();
   wp_die();
}

When the admin page is displayed, I have this:

   echo 'body onLoad=loadDoc();';
   echo 'div id=myDiv/div';
   ?
        script
            function loadDoc() {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function () {
                    if (this.readyState == 4  this.status == 200) {
                        document.getElementById(myDiv).innerHTML = this.responseText;
                    }
                };
                xhttp.open(GET, ajaxurl + ?action=myAction, true);
                xhttp.send();
                setTimeout(loadDoc(), 1000);
            }
        /script
     ?php

It works.

Here's my questions.

Is this the proper way to do this?

Is there a better way to do this instead of polling with setTimeout?

Thanks!

Topic iframe plugins Wordpress

Category Web


Use JavaScript to poll for new data at an interval and update the DOM as it comes in. Downloading the complete log file at intervals would be very inefficient and quite likely consume a huge amount of bandwidth. Instead, use some server-side code to determine if new data is available and if so return that in the response.

For instance, the client could send some information about the last lines it received - say the time at which it last received new data, and the largest line number it already has. The server can then check if the file's modified time is greater than the time at which the client last received data, and if so, open the file and send any new lines to the client.

WordPress's AJAX handlers would be a fine way to implement the JS<=>WordPress communications. The Plugin Handbook's page on AJAX, and the Codex's "AJAX in Plugins" page are good places to start.

The Mozilla Developer Network has a nice intro on DOM manipulation via JS (among many other guides), but otherwise the subject matter in isolation is outside the scope of this Stack.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.