Error: Unable to access property 'outerHTML' of a non-existent element

When attempting to retrieve the content of a table and display it in a new window for printing, I always encounter this error: The table is located within a modal and loaded dynamically into the modal via an Ajax function:

This is the Ajax function:

function view(id){
    var html;
        $.ajax({
          url: "<?php echo site_url('admin/prescription/view_prescription_ajax') ?>/"+id,
          type: 'POST',
          dataType: 'html',
          success:function(data){
            html = data;
          },
          async: false
        });
    $('#view .modal-body').html(html);
    $('#view').modal('show');
}

This is the HTML returned by the code:

$data='';
$prescription = $this->prescription_model->get_prescription_by_id($id);
$template= $this->notification_model->get_template();
$data.='<table width="100%" border="0" id="printTable"  class="pt" style="padding-bottom:0px; height:100%;" >

                <!-- Table content omitted for brevity -->

           </tfoot>    

     </table>


    <div class="form-group no-print">       
         <div class="row no-print">
                <div class="col-sm-4 pull-right">
             <a  class="btn btn-default yes-print no-print" id="print_p"  onClick="printData();" style="margin-right: 5px;"><i class="fa fa-print"></i> Print </a>
             <a href="http://medicalfrequencycentre.com/drsystem/admin/prescription/pdf/'.$prescription->id.' id="pdf" class="btn btn-primary  no-print" style="margin-right: 5px;"><i class="fa fa-download"></i> Generate PDF </a>
                </div>

        </div>
    </div>
    ';

echo $data;

This is the JavaScript function:

function printData()
{
   var divToPrint=document.getElementById("printTable");
   newWin= window.open("");
   newWin.document.write(divToPrint.outerHTML);
   newWin.print();
   newWin.close();
}

Answer №1

It is important to call the print data function on success, as events may not bind properly after dynamic content is added to the DOM later. Additionally, remember to remove the onClick attribute with "printData" from the button.

function displayPrescription(id){
    var html;
        $.ajax({
          url: "<?php echo site_url('admin/prescription/view_prescription_ajax') ?>/"+id,
          type: 'POST',
          dataType: 'html',
          success:function(data){
            html = data;
    $("#print_p").on("click", function(e){ printData(); });
          },
          async: false
        });
    $('#view .modal-body').html(html);
    $('#view').modal('show');
}

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

Issue with Material UI: An invalid value was detected for the select component, even though the value is within the available options

I am facing an issue with a dropdown list component using material UI. The dropdown is populated by an API call and displays a list of departments with their corresponding IDs and names. Upon selecting a record from a table, the department name associated ...

A guide to implementing toggle functionality on child elements

After clicking the button, the entire sidebar toggles, but I only want the side menus to toggle. Here is the relevant HTML code: <nav id="sidebar"> <div class="sidebar-header"> <img src="/fintantra/image ...

jquery is failing to recognize the HTML generated by ajax

Upon successful login, the website displays a button with the HTML code below: <button class="logout-button">Logout</button> The button is also hardcoded into the website's HTML for consistency. However, after refreshing the page, the AJ ...

iPython does not show Folium map due to an error message stating: 'Uncaught ReferenceError: L is not defined'

Attempting to showcase a basic map in iPython using the Folium leaflet library. Recently installed iPython via Anaconda with Folium added through Pip. Verified that everything is fully updated Ran this code in iPython import folium map = folium.Map(locat ...

Trouble with Basic JavaScript Comparison Function

I'm facing an issue with a JavaScript comparison that doesn't seem to be working. It's puzzling why it's skipping to line 12302 and setting showNoDataText = true. The logic dictates that it should be false since the array length of 285 ...

Next.js Error: Unable to access the 'collection' property, as it is undefined

I have recently started using next.js and I am interested in creating a Facebook clone by following YouTube tutorials. However, I keep encountering the error message "Cannot read properties of undefined (reading 'collection')". To troubleshoot, I ...

Using JavaScript and jQuery to replace an image when scrolling

I have a website menu that functions similar to this example: https://jsfiddle.net/sinky/XYGRW/ (found here on stackoverflow) My query is that the designer would like the logo in the navigation bar (home button) to be replaced with a smaller icon. Not jus ...

What is the process for calculating the total sum of dropdown list values?

Here is the JavaScript function I am using: <script type="text/javascript"> $(document).ready(function() { $('#roomOptions select').change(function() { var total = 0; $('#roomOptions select').each(function() ...

Tutorial on inserting a picture into muidatatables

Important Note: The image stored in the database is called "profileImage." I am looking to create a dynamic image object similar to other objects. When I input this code: { label: "Image", name: "profileImage" }, it simply displays the image endpoint as ...

Troubleshooting why content set to a <div> element with JavaScript / jQuery is not persisting after a

This is the current code snippet I am working with: <asp:Button ID="btnSave" runat="server" OnClick="Save" CssClass="StylizedButton" resourcekey="btnSave" /> <div id="lbltot"></div> Below is the JavaScript portion of the code: $(do ...

Adding a JavaScript widget to a WordPress page

Good morning! I need to place an affiliate external widget on a WordPress page. The code I have loads external content within the page. <script type="text/javascript" src="http://www.convert.co.uk/widget/mobiles.js"></script> The placement o ...

Issue with loading CSS and JavaScript following a GET request

I initially used express and the render function to display different pages on my website. However, I've now decided to switch to vanilla JavaScript instead. The objective is to load the HTML file along with all the necessary JS and CSS files. Below i ...

Concealing/Revealing Elements with jquery

For hours, I've been attempting to switch between hiding one element and showing another in my script. Here is the code I am using: <script type="text/javascript"> function () { $('#Instructions').hide(); $('#G ...

The console log is not being displayed in my Redux reducer and it is returning an undefined

I'm facing an issue with my Redux application after integrating JWT into my Nest API. Below is the code snippet from my reducer: export default function reducer(state = {}, action) { switch (action.type) { case 'USER_LOGIN_SUCCESS&apo ...

Issue with jQuery AJAX only sending certain data values

When submitting a form to a Google Sheet using jQuery AJAX, I noticed that some values are not being submitted. Specifically, there are radio buttons that only appear when certain parent radio buttons are selected. Below is the code for my form: <!DOC ...

Issue encountered when making API requests in JavaScript that is not present when using Postman

Currently, I am developing a web application using express and one of the functionalities is exposed through an API with an endpoint on 'api/tone'. This API acts as a wrapper for one of Watson's services but I choose not to call them directl ...

Verify that the user visits the URL in next.js

I need to ensure that a function only runs the first time a user visits a page, but not on subsequent visits. For example: When a user first opens the HOME page, a specific condition must be met. When they then visit the /about page, the condition for th ...

Instructions for submitting three different forms from three separate pages simultaneously

I am facing a challenge where I have 3 forms spread across 3 different pages, with the submit button located on the 3rd page. Is there a way to submit all 3 forms simultaneously by clicking on the submit button? Are there any solutions available in javascr ...

Guide to using AngularJS to upload FormData object

I recently started using angular-js and encountered a problem when trying to submit multipart/form-data with an image. The $http.post() method only supports json format, so I needed to convert the formdata object to json format. $scope.SubmitForm=function ...

Store Dark Mode preferences in the browser's local storage using React and Material-UI

Is there a way to save the dark mode setting in localStorage? Can this approach be used for storing it? Any suggestions on how to achieve this would be appreciated. Thanks, cheers! function App() { const [darkState, setDarkState] = useState("&qu ...