Leverage the event manager to automatically reload the page upon detecting a specific string

I currently have this code in place to update a codebox on the page with data retrieved from dyntask.php.

<script type="text/javascript">
if(typeof(EventSource)!=="undefined") {
    var eSource = new EventSource("dyntasks.php");
    eSource.onmessage = function(event, previous) { 
        document.getElementById("serverData").innerHTML = event.data; 
    };
}
</script>

The data fetched from dyntask.php is sourced from a text file containing updates like:

2018-05-10 14:02:01: starting task 99333
2018-05-10 14:02:03: task 99333 completed
2018-04-13 15:13:44: triggered tasks
2018-05-10 14:05:52: starting task 99334
2018-05-10 14:05:57: task 99334 completed
2018-05-10 14:11:01: starting hidden task 99335
2018-05-10 14:11:07: hidden task 99335 completed
updating...

The last line of the text file always reads "updating...". The requirement is to constantly monitor the second to last line for changes:

  • The monitoring should commence whenever the keyword "starting" appears in a line
  • Once that keyword is detected, the script should then search for the occurrence of the word "completed"
  • If "completed" is found, the script should trigger a full page refresh

My JavaScript knowledge is limited to what was necessary to create this script. I am hopeful that someone proficient in JavaScript can add just TWO lines to make it work as intended.

Could you please offer some guidance?

Answer №1

If you're uncertain about the required format and feel like the regex could be improved, this code snippet is a good starting point for extracting the value from the last line before the "updating..." message.

var text = `2018-05-10 14:02:01: starting task 99333
2018-05-10 14:02:03: task 99333 completed
2018-04-13 15:13:44: triggered tasks
2018-05-10 14:05:52: starting task 99334
2018-05-10 14:05:57: task 99334 completed
2018-05-10 14:11:01: starting hidden task 99335
2018-05-10 14:11:07: hidden task 99335 completed
updating...`;
var regex = /(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}:)(.*?)\n(updating)+/;

var result = regex.exec(text);

document.write(result[1] + ' ' + result[2]);

Answer №2

SUCCESS ACHIEVED!

<script type="text/javascript">
if(typeof(EventSource)!=="undefined") {
    var eSrc = new EventSource("dynamic_tasks.php");
    eSrc.onmessage = function(event, prev) { 
        document.getElementById("serverData").innerHTML = event.data; 
        var dataContents = event.data.split('<br/>');
        if(dataContents[6].indexOf('completed') !== -1 && dataContents[6] != localStorage.getItem('previous') && previous !== '') {
            window.location.href = '/home.php?id=taskmanager';
        };
        localStorage.setItem('previous', dataContents[6]);
    };
}
</script>

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

The development mode of NextJS is experiencing issues, however, the build and start commands are functioning normally

Just finished creating a brand new Next app (version: 12.0.7) using Typescript and Storybook. Everything seems to be working fine - I can successfully build and start the server. However, when I try to run dev mode and make a request, I encounter the follo ...

Reloading Web Page with WebDriver while Awaiting a Specific Condition

Is there a more elegant way to refresh a webpage during tests using Selenium2 instead of sending the F5 key? I am wondering if the driver has a method for refreshing the entire webpage. Here is my code: while(driver.findElements(By.xpath("//*[text() = &ap ...

Differences between Cypress and JQuery objects, and the significance of the cy.wrap function

Currently diving into cypress and experimenting with various testing methods. If anyone could lend me a hand with the following inquiries: 1. I've come to understand that most cypress objects utilize jQuery objects for DOM operations, but what sets t ...

How to efficiently deliver a document to a user using the MEAN stack

The express controller code snippet I'm working with involves creating a CSV file and sending it back to the user: // Correct file path and write data var currentDate = new Date(); var storagePath = path.join(__dirname,'../../public/reports/&apo ...

Tips for adjusting HighCharts layout with highcharts-vue integrations

I have a fairly simple component: <template> <div> <chart v-if="!loading" ref="priceGraph" constructor-type="stockChart" :options="chartData" ...

Adjusting the focus of an element with jQuery based on coordinates and offset values

jQuery.fn.getCoord = function(){ var elem = $(this); var x = elem.offset().left; var y = elem.offset().top; console.log('x: ' + x + ' y: ' + y); ); return { x, y }; }; This custom jQuery funct ...

Does binary search maintain its usual efficiency?

Does binary searching remain efficient and effective if an array inherits from an object? ...

Forcing an Ajax Load - A Guide to Compelling Loading

I'm attempting to load a page and place it within a div. example code: $("#test").load("page.php"); The issue arises when upon loading, sometimes if I run the script again, it appears that the file 'page.php' is not actually being reload ...

Ways to troubleshoot the error "push of undefined cannot be read" in Firebug Lite?

While attempting to open Firebug Lite for testing an AngularJS application in Chrome on OS X (Maverick), I encountered an issue. An error message appeared: cannot read property 'push' of undefined firebug-lite.js 30905 What steps can be taken t ...

Concealing Content within an Accordion

Looking for some guidance on setting up a mobile version of my product image with hover features. Currently using tooltips on desktop and planning to use a modified accordion on mobile, but struggling to make progress. Customized some JS to toggle an acco ...

Display a helpful tooltip when hovering over elements with the use of d3-tip.js

Is it possible to display a tooltip when hovering over existing SVG elements? In this example, the elements are created during data binding. However, in my case, the circles already exist in the DOM and I need to select them right after selectedElms.enter ...

What is the reason behind Node's error callback returning undefined first?

Whenever I try to run the error callback function, the code below returns undefined. I'm puzzled by why the JSON isn't being returned when the console log displays the entire query. Take a look at the function that is triggering the json to be l ...

What is the best way to call a method within a TypeScript class using its name as a string while already inside the class itself?

Currently, I am developing a class that automates the creation of routes for Express and invokes a function in a controller. However, upon trying to execute this[methodName](req, res), I come across an error message stating: 'Element implicitly has an ...

jQuery UI Slider: Enable handles to move across each other

I have implemented a customized range slider on my webpage located at (see 'Day & Night Shift') to work with hours and minutes in 15-minute increments. $(function() { $("#slider-range").slider({ range: true, min: 0, ...

Looking to incorporate new values without replacing them in react.js and mongoDB

function getFilterQuery() { const completedWorkState = WorkflowStates.findOne({title: 'Completed'}); const inProgressWorkState = WorkflowStates.findOne({title: 'In Progress'}); const identifiedWorkState = WorkflowStates.findOne ...

What occurs to the node request stream before it is utilized?

Currently, I am developing a node application that involves piping the body of a post request into a writable stream for saving data to disk. While working on this project, it has come to my attention that I lack knowledge about what happens to the request ...

dojo.js is throwing a multipleDefine error when using qwest.js

Having some trouble loading qwest.js with the dojo (ArcGIS) AMD loader, encountering a multipleDefine error. require([ // `../vendor/react/react.js`, // this works fine `../vendor/qwest/qwest.min.js`, // this causes error ], ( // React, qwest, ) ...

JS - Activate the ghost element feature by using the preventDefault function

I am currently working on a project where I need to drag elements from a list of img tags to various svg:rect containers. The process involves using mousedown and mouseup events to track which img is being picked from the list and where it is dropped with ...

Monitoring changes in the DOM with AngularJS

I have a unique situation where I need to monitor and recompile the entire DOM of a page whenever it undergoes any changes. While AngularJS handles this through databindings, I require a solution that goes beyond just bindings. My app is constructed using ...

Looking for a way to efficiently retrieve results by matching multiple string keywords as you go through each line of a file (fs)?

Essentially, I have multiple search strings provided by the client that need to be matched with each line in a file. If a line matches all of the inputted strings, I should add that line to the results array. However, when I run the code below, it only ret ...