Exploring ways to retrieve a parent div from a child window

Within my parent window, I have a div where I want to display newly entered records that are added into the database.

The following code snippet represents the div within the parent window:

<div id="divTable"></div>

A button resides in the child window with the purpose of triggering an update function:

<input type="button" name="submit" value="Submit" onclick="updateTable();"/>

Additionally, there is an external JavaScript file containing a function for updating the table after data entry:

function updateTable()
{
 if(insertThis()==true)
 {
  alert("Your details have been successfully submitted! Please click 'View' to see all records.");
 }
 //What should be included here?
}//updateTable(w, h)

Amidst the JavaScript functions, there exists another script dedicated to displaying the table through AJAX:

function displayTable()
{
 var page = "database.php"
 var parameters = 'action=update';
 var xmlhttp = new XMLHttpRequest();

  if(xmlhttp==null)
  {
   alert("Unfortunately, your browser does not support AJAX!");
   return false;
  } 
  xmlhttp.onreadystatechange=function()
  {      
   document.getElementById("divTable").innerHTML=xmlhttp.responseText;
  };
  xmlhttp.open("GET", page+"?"+parameters, true);
  xmlhttp.send(null); 
}//displayTable()

Moreover, a PHP file specifically handles the insertion of queries into the database. In the child window, text fields and radio buttons are provided for user input according to database requirements.

For the updateTable() function, what should be implemented? Should it include the displayTable() function or utilize other methods like windows.opener? Researching online led to various examples, but they lack guidance on using external JavaScript files. This has caused some confusion. The goal post-user submission is immediate display of the table upon clicking the 'Submit' button. Currently, an additional button is utilized in the parent window to view the table again after exiting. The desired outcome is to eliminate this step and directly display the table at the designated div section.

To ensure clarity, in the displayTable() function,

document.getElementById("divTable").innerHTML=xmlhttp.responseText;
facilitates the table rendering. Is reusing this function recommended?

P.S. Preferably seeking solutions utilizing raw JavaScript due to limited exposure to jQuery as a beginner in the programming language.

Answer №1

If you want to reconstruct the table, simply run the displayTable(); function again:

    function updateTable()
    {
     if(insertThis()==true)
     {
      alert("Your information has been added! Click on 'View' to see all records.");
      //You should put it here:
      window.opener.displayTable();
     }
     //Need to figure out what to add here.

    }//updateTable(w, h) 

Another suggestion is to change the body tag in your parent page like this:

<body onload="displayTable()">

In the script of your child page, reload that page:

function updateTable()
        {
         if(insertThis()==true)
         {
          alert("Your details are now saved! Click on 'View' to see all records.");
          //You should put it here:
          //window.opener.displayTable();
          window.opener.location.reload();
         }
         //Need to figure out what to add here.

        }//updateTable(w, h) 

Answer №2

When working with external JavaScript, it's important to avoid hardcoded references to elements in the resulting document. This is because when the JavaScript is initially loaded, the document has not yet been fully rendered and its structure is unknown.

If you need to manipulate elements in the document using JavaScript, it's best to wait until the document is fully loaded before doing so. You can achieve this by passing the finished object to a function once the document is ready.

For example, if you have a function that modifies a table element, you would call it like this:

updateTable(opener.document.getElementById('divTable'));

Within the function, you would use a variable to reference the specific object you want to manipulate. This way, your code will work correctly after the document has finished loading.

window.onload=function(){
    opener.document.getElementById('divTable').style.visibility ="hidden";
    opener.document.getElementById('divTable').innerHTML='Hello, World';
    opener.document.getElementById('divTable').style.visibility ="visible";
}

This JavaScript code should be included in the final HTML document of the child window being loaded, within a <script> tag.

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

Tips for replicating PaddingTop using Grid Material UI and populating blank rows at the beginning

Imagine we are working with a Grid component const App = () => { const useStyles = makeStyles(theme => ({ root: { flexGrow: 1 }, paper: { padding: theme.spacing(2), textAlign: "center", color: theme.palette.tex ...

What is the process for retrieving data from a website?

Currently, I am in the process of setting up an automated test using the basic page object pattern. The objective is to open Google, input a search query, click on a link from the results, and retrieve the information. So far, I have successfully navigated ...

What are the steps to successfully implement "Pointermove" event delegation in Safari iOS for parent/child elements?

I've encountered an issue that I'm struggling to find a solution for. My goal is to implement an event delegate using pointermove on a parent container, and I need to be able to detect when the event transitions between a child element and the pa ...

What methods can I employ within an AngularJS controller to retrieve data from Google App Engine instead of solely relying on a JSON file?

As a newcomer to web development, I have been experimenting with retrieving data from a Google App Engine datastore and selectively displaying it on a webpage using AngularJS. While I have successfully integrated Angular with a JSON file and posted the con ...

PHP service encountering a failure during an AJAX call

After setting up a web service with PHP, I found that when accessing it from a rest client, the JSON response is correct. However, when calling the method from an AJAX call integrated into a Drupal site, the service response comes back as HTML, leading to ...

React animation failing to render underline animation

After tinkering with the underline animation while scrolling down on Codepen using Javascript, I successfully implemented it. You can check out the working version on Codepen. This animation utilizes Intersection Observer and a generated svg for the underl ...

window.print function appears multiple times

Looking for help with a sample script I have that prints a section of my website page when a button is clicked. The issue arises when using ajax to transition and clicking the same button results in window.print activating multiple times. How can I ensur ...

Tips for refreshing the default style of Material UI select

I'm having trouble customizing the default background color of the first menuItem in the select component. The class I need is not visible when inspecting the element, as the background color disappears upon inspection. Steps to reproduce: 1. Click ...

Error message: CodeIgniter DataTables index is not defined

While I have used datatables in the past, this error is new to me. The errors I am encountering are: Message: Undefined index: order Message: Undefined index: start Message: Undefined index: length Message: Call to a member function result_array() o ...

Updating specific data in MongoDB arrays: A step-by-step guide

{ "_id":{"$oid":"5f5287db8c4dbe22383eca58"}, "__v":0, "createdAt":{"$date":"2020-09-12T11:35:45.965Z"}, "data":["Buy RAM","Money buys freedom"], & ...

The functionality of Material UI tooltip is not functioning properly when accessed on mobile devices

Attempting to transform Tooltip into a controlled component that relies on the onClick event. While this setup works well on mobile and web, it loses its original functionality of showing the Tooltip on hover. Is there a way to make the Tooltip function ...

What is the best way to navigate to a new page following an ajax request in AngularJS

I have implemented angularjs and nodejs in my project to handle authentication. After a successful background authentication, I need to know how to redirect the user to the dashboard. Below is the login section of my code: <div ng-controller="loginCt ...

Adding a see-through Bootstrap Navbar to a Fullpage.js website: A step-by-step guide

I am trying to incorporate a transparent Bootstrap Navbar into my page that is using fullpage.js. The desired outcome is for the navbar to stay on top of the page without affecting the layout of the website content. I have referenced an example here, but ...

In need of an AJAX image viewer compatible with PHP or considering transforming an ASP image viewer to PHP

Currently, I am in search of a Javascript (preferably based on jQuery) Ajax image viewer with a zoom feature that is compatible with PHP. The closest match to what I require is a script called "thinDoc" which I found to be very impressive: thinDoc To se ...

Using Asp Core to implement Ajax Post with ViewModel

I am currently working on a project using Asp Core and I am facing an issue with Ajax posting a filepicker blob Javascript Object back to an action for uploading the image to Amazon S3. Despite trying various methods, I have been unsuccessful in making it ...

Adjusting the maximum character limit of the text input field

After receiving some values from C# via AJAX, I need to bind them to a GridView. Everything is working fine, but the only difference is that instead of binding the value to a textbox's property, specifically the MaxLenght property, it needs to be boun ...

Node.js is unable to handle the contents of an SNS event message

I am encountering an issue while attempting to extract content from a Message in an SNS event within a Node.js Lambda project Below is the code snippet for processing the message: exports.handler = (event, context, callback) => { var message = event. ...

Where to Locate a String Excluding <a> Tags?

I'm in the process of writing a JavaScript code that will scan an HTML document and identify all occurrences of a specific keyword that are NOT contained within a link, meaning not under an <a> tag. To illustrate this, let's examine the fol ...

Error: The fetch request was unsuccessful [NextJS API]

I keep encountering an error - TypeError: fetch failed after waiting for 300 seconds while requesting an optimization server that requires a response time longer than 300 seconds. The request is being sent from the provided API in NextJS. Is there a way ...

Start a fresh project using the Teamweek API with jQuery integration

After successfully acquiring the planning details from Teamweek using the API (Get projects from Teamweek in jQuery), I am now looking to feed Teamweek a project. Even though the code below seems to work (based on the response received), I am unable to lo ...