The AJAX response enters a continuous loop if it contains the window.print function

I'm looking to print the screen upon receiving an ajax response. Here's my code snippet:

function initiatePrint() {
        var request  = new XMLHttpRequest();
        request .open("GET", "printPage.html", true);
        var counter = 0;

        request.onload = function() {
            if (request.status >= 200 && request.status < 400){
                console.log("success");

                window.print();

            } else {
                // We reached our target server, but it returned an error

            }
        };

        request.onerror = function() {
          // There was a connection error of some sort
        };

        request.send();

      }

However, I'm encountering an issue with an infinite loop on the response (seeing "success" multiple times in the console), almost as if window.print() is triggering the same ajax call again. What could be causing this and how can I successfully print the page?

Answer №1

It seems like the code is placed in the global scope.

In JavaScript, all global entities such as functions and variables are considered properties of the global object. This global object is referred to as window in browser environments*. By naming your function as print, you are essentially replacing the default window.print function with your own. Therefore, when you call window.print within your function, it invokes your custom function instead of the standard window.print.

To avoid this issue, simply rename your function to something different.


(* In browsers, the term window is used to refer to the global object. Technically, window is a global variable that serves as a reference to the global object itself.)

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 alert() function in PHP does not function as expected and instead prints to the console

My attempt to display an alert is not working and I'm not sure what I might be missing. Can someone please help me pinpoint the issue? //my.php if(mail($to, $subject, $message, $headers)) { $message = "Mail sent."; echo "<script type=&apo ...

I need help in updating my user information using jQuery, JavaScript, AJAX, and the Node.js API

Working with a dynamic table that fetches JSON data from the API (/api/dashboard/v1) using the GET method. There is another API (/api/updateUser/v1:id) available for updating user information using the PUT method. A table has been created with an Edit op ...

Experimenting with applying jquery .slideDown() to multiple classes in order to create dynamic animations

I am facing an issue while using .slideDown() with multiple classes. I want only one class to toggle/dropdown at a time, but currently when I press the button, all classes show up instead of just the one I want to display. How can I achieve this? Here is ...

Creating multiple React applications using shared configuration files: A step-by-step guide

I am in the process of developing a React app, and my goal is to create multiple React apps that share the same configurations - including modules and configuration files like tailwind.config.cjs. How can I modify my environment to achieve this? My plan i ...

I am experiencing difficulties with broadcasting and attending events

File.js scope.menuItemClick = function (def, callbackText, keepMenuOpen) { console.log(def); if(def.automationId === "Print"){ console.log("before send"); $scope.$root.$broadcast("printingData","my Data"); console.log("after send"); } Nex ...

Trouble with parsing JSON in NodeJs

I have a JSON file containing the names of people that are stored. Using the Node Manager's filesystem, I read the content from this file and attempt to convert the JSON to a string and then parse it into a JavaScript object. However, after parsing it ...

Utilizing BBC gelui within Joomla 3.0 for seamless integration

I am currently using Joomla! 3.0 with the Joomlashape Helix template and I am following a tutorial. You can check out the tutorial here. The tutorial mentions that I need to download RequireJS. Can anyone confirm if RequireJS is compatible with Joomla 3 ...

Adding the API JSON response to the MetaInfo in Vue.js

i am dealing with a meta tag that has the following structure metaInfo () { return { title: 'my title', meta: [ { name: 'description', content: 'my description' }, ...

What is the best way to showcase Vue data of a selected element from a v-for loop in a

Here is an example of how my json data is structured. I have multiple elements being displayed in a v-for loop, and when one is clicked, I want to show specific information from that element in a modal. [{ "id": 1, "companyNa ...

Implement a jQuery click event on a dynamically generated button in the code-behind

A button (Replybtn) is dynamically created when clicked in the code-behind file. --Default.aspx.cs-- protected void ReloadThePanelDetails_Click(object sender, EventArgs e) { litResultDetails.Text = litResultDetails.Text + "<button id='Replyb ...

Passing properties from the parent component to the child component in Vue3JS using TypeScript

Today marks my inaugural experience with VueJS, as we delve into a class project utilizing TypeScript. The task at hand is to transfer the attributes of the tabsData variable from the parent component (the view) to the child (the view component). Allow me ...

Utilizing jQuery Deferred or Promise to synchronize the completion of multiple asynchronous $.post requests

I'm attempting to make three separate jQuery posts, storing their results in variables that are accessible outside of their scope. Once all three posts have returned successfully, I want to execute another function. Currently, I am using nested callba ...

React components to separate static PDF pages

I have successfully implemented a feature in my React App that allows me to export a long page in PDF format using html2canvas and jsPDF. The code snippet for exporting the page is as follows: html2canvas(document.body).then((canvas) => { var img ...

Creating engaging video call games using React-Native

I need assistance with developing a react-native video call app using agora.io. I want to incorporate interactive games for users to play during the calls, similar to those available on Facebook messenger. Can anyone point me towards helpful resources or t ...

Display or conceal a text field in Vue 2/Vuetify 1.5 depending on whether a checkbox is selected, with the possibility of duplicated

I've created a product checkbox selection feature that dynamically shows or hides text fields based on the user's selection. Unfortunately, there is a glitch in the system where selecting the second item causes duplication of text fields from th ...

Engaging with the CSS content attribute

Below is a code snippet that inserts an image before the header tag. Is there a way to incorporate JavaScript or jQuery in order to execute certain actions when the inserted image is clicked? h1::before { content: url(smiley.gif); } The HTML code fo ...

Having trouble accessing the Ajax "data" parameter in Twisted

An ajax request is made using the "POST" method with these parameters: function sendDataToServer(portNumber){ console.log(portNumber) $.ajax({url: "action", dataType : 'html', type: "POST", data: portN ...

Using only CSS to reverse the order of Bootstrap rows within a forEach statement in a .php file

I am facing a challenge in reversing rows within a forEach statement. For instance, in the first row, the content's div (title, text) should be on the left side and the image on the right side. In the second row, it should be reversed, with the image ...

What is the best way to individually open dropdowns in React?

I am facing an issue with dropdowns in a list where clicking one dropdown opens all others due to their state being the same. I believe using ids could be a solution, but I am not sure how to implement it correctly. The project utilizes reactstrap, so I ...

Location-based services: Updating the position of a Google Maps marker without refreshing the entire map interface

How can I update only the marker on a map when the device is in motion or has increased accuracy? I want to reload the map when the position changes, but only move the marker. Below is the code snippet that I currently have: if (navigator.geolocation) { ...