Retrieve the javascript code from a different page using Ajax and xmlHttp.open

I have a JSP page called DEMO1.jsp where I've implemented AJAX code to refresh every minute. In DEMO1.JSP, the code snippet looks like this:

<head>

    <script type='text/javascript'>
        setInterval(function(){
            document.getElementById('bgframe').contentWindow.myInternalFunction();
        }, 5*1000);

    </script>
</head>
<body onload="AutoRefreshValid();"  style="margin:1px;font-family: Serif, Arial, Times, serif;" id="ValidWaybills"><center>

    <iframe id='bgframe' style='display:none;' src='DEMO2.jsp'></iframe>

    <script type="text/javascript">
        function AutoRefreshValid(){
            var xmlHttp;
            try{
                xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari
            }
            catch (e){
                try{
                    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
                }
                catch (e){
                    try{
                        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch (e){
                        alert("No AJAX");
                        return false;
                    }
                }
            }

            xmlHttp.onreadystatechange=function(){
                if(xmlHttp.readyState==4){
                    document.getElementById('ValidWaybills1Valid').innerHTML=xmlHttp.responseText;
                    setTimeout('AutoRefreshValid()',5*1000);
                }
            }

            xmlHttp.open("GET","DEMO2.jsp",true);
            xmlHttp.send(null);



        }
    </script>
    <div  id="ValidWaybills1Valid">

    </div>

In DEMO2.JSP, I've written JavaScript code that needs to run using AJAX in DEMO1.jsp without reloading the page every 5 seconds. Here is the code from DEMO2.jsp:

<head>


    <script type="text/javascript">
        function callme3(){

        <%  Date d1 = new Date();
        %>
                alert("Date is          <%=d1%>");
            }
    </script>
</head>
<body onload="callme3()">



</div>

Thank you and regards, Sudarshan

Answer №1

An XML Http Request is responsible for sending and retrieving data, but not for executing the retrieved data.

Below is a simplistic solution to your issue, although it is not recommended:

xmlHttp.open("GET", "SU3.jsp", true);
xmlHttp.onload = function(evt) {
  var div = document.createElement('div');
  div.innerHTML = evt.target.responseText;
  document.body.appendChild(div);
};
xmlHttp.send(null);

This code will cause the browser to crash after an extended period of time.

The correct approach is to have SU3.jsp return data in JSON or plain HTML format and handle all logic in SU2.jsp.


Based on the most recent information provided (which should ideally be included from the initial version), the solution is straightforward and effective.

In Su2.jsp, add the following code:

// assuming 'map' refers to the map object.
// Using jQuery for clarity, but using XMLHttpRequest directly is also acceptable.

var timer = null;

function updateMarker() {

  $.get('su3.jsp', function(data) {
    for (var i = 0; i < data.length; i++) {
      var datum = data[i];
      new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(datum.pos.lat, datum.pos.lng),
        title: datum.title
      });
    }
    // After all tasks are completed, set a timeout for the next update.
    // Use setTimeout() instead of setInterval() to accommodate network latency.
    timer = setTimeout(updateMaker, 5000);
  });

}

// This should be called within the onLoad() handler.
updateMaker();

In SU3.jsp, ensure that the data is output using Content-Type: application/json, displaying marker information like so:

[{"pos":{"lat":-25.363882,"lng":131.044922},"title":"Australia"}]

Answer №2

To run javascript from SU3.jsp, consider using a hidden iframe in SU2.jsp to call it.

Include the following JavaScript/Markup code in SU2.jsp

<html>
<head>
  <script type='text/javascript'>

    setInterval(function(){
        document.getElementById('bgframe').contentWindow.location.reload();
    },60000); // refresh every 60 seconds

  </script>
</head>
<body>
    <iframe id='bgframe' style='display:none;' src='SU3.jsp'></iframe>
</body>
</html>

Keep in mind that if SU3.jsp needs access to functions/variables within its parent (SU2.jsp), you should use window.parent. More details can be found here

If you simply need to execute a JavaScript function within SU3.jsp every 60 seconds, you can achieve this with the following code:

document.getElementById('bgframe').contentWindow.myInternalFunction();

setInterval(function(){
    document.getElementById('bgframe').contentWindow.myInternalFunction();
}, 60000);

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

Developing a universally accessible variable for utilization in various functions

I'm having trouble understanding why 'currentPos.LatLng' is undefined when trying to access it outside the function even though it's part of an object. I want to be able to retrieve the current position values to use them in another fun ...

What is the best method to extract the values of objects in an array that share

var data= [{tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, ...

What is the best way to delete a container when its child element includes a specific string?

I run a website that compiles video clips from various sources, including YouTube. Occasionally, some clips appear as private videos. I am looking to use jQuery to apply the display:none; property to the entire div when the class a.colorbox.cboxElement con ...

Having trouble getting JavaScript validation to function properly

I'm struggling to make validation work properly when hitting the submit button. No alert messages appear, even though I should be receiving alerts for empty fields. Can someone identify what is wrong with my code? I have tried checking the validation ...

I keep encountering a 404 error page not found whenever I try to use the useRouter function. What could

Once the form is submitted by the user, I want them to be redirected to a thank you page. However, when the backend logic is executed, it redirects me to a 404 page. I have checked the URL path and everything seems to be correct. The structure of my proje ...

Managing the Navigation Bar

I am currently using Bootstrap and ReactJS, and I am facing an issue where the active tab on the navigation bar does not change when I scroll down the page. At the moment, the active tab only changes when I click on a specific section. Each section corresp ...

Displaying a PDF in a new browser tab using JavaScript after retrieving data with cURL

Seeking guidance here. I currently have a URL for Phantomjs that produces a PDF, but my goal is to generate the PDF on the server side. <script> $("#generatePDF").click(function(){ var fullLink = "<? echo $link ?>" $.ajax({ ...

What is the best approach for retrieving values from dynamically repeated forms within a FormGroup using Typescript?

Hello and thank you for taking the time to read my question! I am currently working on an Ionic 3 app project. One of the features in this app involves a page that can have up to 200 identical forms, each containing an input field. You can see an example ...

JavaScript code snippet to remove a specific element from an array and store it in an object

I am looking to convert an array into an object, where each item in the array is separated into categories as shown below. let a=['monkey: animal','John:human', 'Rob:human', 'donkey:animal'] I expect the output to b ...

Updating Page Content with JQuery AJAX Post Without Page Reload

So I realize I may be asking a question that has been asked before, but as a complete beginner with AJAX jQuery, I'm not sure what to search for. I've tried searching without success, so please bear with me. I have a PHP WordPress site that defa ...

Tips for displaying unformatted text using HTML

Is there a way to display a string in HTML with all of its escape sequences preserved? For example: eipt No. : 1995,\nmount 935\nAdm. : 17/06/2016 INSTRUCTIONS : 1) This card is valid only for the student's name & for the period indic ...

Steps for establishing a one-to-many relationship in my comment database table

I've inserted the following code into my articles migration: Schema::create('articles', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('user_id'); $table->foreign('user_id')- ...

Is it possible to read a file with a different dynamically generated name each time in Cypress?

Being new to Cypress, I am faced with the challenge of writing a test case to verify the download of a file. Despite researching various resources on similar test cases, they all involve reading a file with a static name. In my scenario, the file is downlo ...

Creating a worldwide directive using AngularJS

I'm currently working on implementing a directive that will manage user interaction with the navigation system on my website. The directive includes an element.click event listener in the link function, which is responsible for toggling the display of ...

Getting the unique identifier of a newly generated object using AJAX post request

I have successfully implemented an AJAX post function, but I am facing an issue with the remove button. I need to include the object's ID in the value of the remove button so that my removeFriend function can accurately delete the corresponding row. f ...

Clearing a textarea in jQuery that is populated with text

Having an interesting dilemma. I'm trying to clear a <textarea> and then replace it with new content. The functions in the JSFiddle will work perfectly fine if the textarea is left empty, but as soon as any text is manually typed into it, the me ...

Guide to creating a personalized matcher in Jasmine

Trying to create a Custom Matcher that checks for a specific number of occurrences of a particular string within another string. Here's my approach: var customMatcher = { checkOccurrences: function (expectedString, expectedCount) { return ...

Tips for dynamically adding divs inside a parent div until its width and height are fully utilized

Background: At this moment, I am in the process of creating a webpage where users will input tile width & height along with floor width & height. The aim is to calculate the area of the floor, with tiles measured in inches and the floor input measured in f ...

Best practices for distinguishing between template and style for mobile and desktop in Angular 2 components

Creating templates for mobile and desktop requires unique designs, but both share common components. To ensure optimal display on various devices, I plan to store separate templates and designs for mobile and desktop in distinct files. The goal is to inc ...

Triumph with AJAX and jQuery, yet nothing altered

Recently, I came across a situation where I was reading a text file from the local WAMP server. I tried making some changes to this text and then attempted to send it back to the file. However, even though the AJAX request triggered the success function, ...