Using document.write within a JSONP callback

My current project involves making a cross domain request using the script tag hack and jsonp. In the callback function, I am attempting to write the received data to the DOM using document.write().

Although I am aware that it is recommended to use appendChild/innerHTML instead of doc.write(), I am facing a constraint where I do not have a class/id hook to the element I need to write to. As a result, my only option is to utilize document.write() to write "in place".

The following code snippet can be found within an HTML div enclosed in a script tag:

function request_jsonp(){
var script = document.createElement('script');
var server_path = 'http://somedomain.com/?q=querystring&callback=request_callback';
script.setAttribute('src', server_path);
document.getElementsByTagName('head')[0].appendChild(script);
console.log('data requested');
// document.write('hello world'); // this gets written
}


function request_callback(data){
    console.log('data received');
    document.write(data);
}


 request_jsonp();

 window.onload = function(){
     console.log('onload fired');
 }


/* 
above code prints

data requested
data received
onload fired
*/

Despite experimenting with document.write including a static string inside the callback function, the function seems to be ineffective. I initially believed that invoking document.write before the onload event would successfully insert text onto the page based on information from JavaScript and HTML Script Tags

What could be causing the issue with document.write() not being able to write to the DOM? Furthermore, are there alternative methods or better approaches to achieving this task?

Answer №1

It's important to keep in mind that when you use document.write();, it automatically triggers a document.open();, essentially wiping out any existing content in the document. Attempting to add content to a document with document.write(); is not feasible. However, you can utilize document.write(); to write an entire new document.

There are several potential solutions available:

  • You could pass the target element as a GET parameter, as mentioned by @kirilloid.
  • You might choose to insert an IFrame object at the desired location and then update its content using myIFrame.document.write();.

This issue arises because you are trying to modify the contents of a container that serves as the parent to your script code but hasn't been closed yet.

Alternatively, it's entirely possible that I may be completely off base here. ;-)

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 encountered during installation of the robotjs npm package

Would appreciate any assistance with troubleshooting this issue. I've been grappling with it for 3 days, putting in countless hours of effort. The problem arises when attempting to install the robotjs npm package, as errors keep popping up. I've ...

Using enums in templates - The statement will constantly evaluate to 'true' because the categories of 'RequestStatus.Done' and 'RequestStatus.Rejected' do not intersect at all

My HTML code is in this format, and I want to check the value to display a different form based on certain conditions. I have set up the condition in my HTML like this: requestStatus = RequestStatus; <ng-container *ngIf=" (model.lastStat ...

Error: An unidentified type was encountered that is not a functioning element within an anonymous PHP JavaScript function

Hello everyone, I am seeking help with a JavaScript error that is causing some trouble. Whenever I try to sort a table and implement pagination in PHP, I get an error message in the console stating "Uncaught TypeError: undefined is not a function." Despite ...

Experience a single scene from different perspectives with separate cameras in three.js

I'm looking to recycle a scene by rendering it in two divs with distinct camera angles for each one. This resource mentions that a scene cannot be shared across multiple renderers, and recommends using multiple viewports with a single renderer instea ...

What are some methods for postponing a SurveyMonkey survey prompt?

Seeking feedback on a new site launch in beta mode (full launch scheduled for March 28). We want to give users time to explore the site before showing a pop-up after 10 seconds. As I am new to coding JavaScript, any assistance would be greatly appreciated. ...

An issue arises when trying to loop using a while loop within an HTML structure

I have a small project with a predefined format, where I need to select a value from a dropdown menu and use that value to fetch data from a database and display it in HTML. While I am able to retrieve the data from the database based on the selected value ...

One efficient way to handle multiple concurrent tasks in NodeJs is by using the forEach method to iterate

Having trouble getting the promises to return any values, as they are coming back empty. Despite following suggestions on Stack Overflow, I am still unable to resolve this issue. Frustration levels are high and I'm feeling lost; Can anyone help me pi ...

Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing? Below is the code snippet: HTML <div *ngIf="tempThermometer | async as temp; else loading"> <ng-container *ngIf="temp.length !== 0; else noItems"> &l ...

Unable to find '/images/img-2.jpg' in the directory 'E:React eact-demosrc'

My code is giving me trouble when trying to add an image background-image: url('/images/img-2.jpg'); An error occurred during compilation. ./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src?? ...

Tips for incorporating images from Jade files when using CSS in Node.js rendering:

I am currently working on a Node.js project with the following directory structure: /web /views /css asc.gif bg.gif desc.gif tablesorter.css index.jade search.jade server.js Within my server.js file, I render the s ...

Ways to extract information from a URL when utilizing JQuery code

Code snippet: $(document).ready(function(){ $(".uni_type").click(function(){ uni_type = this.id; location.href = "filter-colleges.php?uni_type="+uni_type; }); }); HTML code: <ul> <li class="uni_type" id="central univ ...

Difference between ng-controller variable and ng-init variable

When working with the code snippet below in angularJS, <script type="text/javascript"> angular.module('app').controller('add', ['$scope',function($scope) { $scope.name = "Bonita Ln"; }]); </script& ...

Error in Asp.net: 'test' is not defined in Microsoft JScript runtime

I'm encountering an issue with an ImageButton that has an onclientclick() method. Whenever I click the button, I receive the error Microsoft JScript runtime error: 'test' is undefined. Below is the full code snippet: <%@ Page Langua ...

The submit button seems to be unresponsive or unreactive

As a newcomer to Angular 2 and Typescript, I am in the process of building a web application. I have created several input fields and, following user submission via a button, I want to log the inputs to the console. However, it seems like my button is not ...

Looking to duplicate a row of input fields while maintaining the same validation rules as the original row?

form <form action="assign_web_menu_action.php" method="post" name="form1" id="form1" > <table id='menuAssign'> <tbody> <tr class="clone_row"> <td> <input type="text" name="menuname[]" id="menuname1" ...

Gathering all the indicated whole numbers from a string and placing them in an array

Upon decoding the URL query using decodeURIComponent and splitting it, the resulting array looks like this: ["pcs_availability:Online", "price:[1500 TO 1999.99]"]. I am trying to extract the proper integers from this array as shown in [1999.99]. In some ca ...

When utilizing ES6, my HTML elements do not have event listeners re-attached to them unless I refresh the page

So, I have a task where I am displaying a simple string on the screen. The goal is that when you click on any letter in the string, it should be removed from its current position and added to the end of the string. However, after clicking on a letter and u ...

Saving game data from local storage to populate the player leaderboard

I have successfully developed a game in which users can play and their scores are stored locally. However, I am facing a challenge in figuring out how to showcase the scores of all users in a table on the Rankings page. Player Ranking Page <?php inclu ...

Utilize JSX components within the strings file

How can I integrate jsx components into a strings.js file in React and React Native? Storing copy-text for an app in a strings.js file is effective for regular text. However, when the text includes other React components, it poses a challenge. For instan ...

Using NGRX Effects to Load Data for a Specific Item in Angular

On my website, there is a page that displays a range of products from the store managed by a reducer called products. When an action PRODUCTS.LOAD_ALL is dispatched, it triggers an API call through an effect and then sends a PRODUCTS.LOAD_ALL_SUCCESS actio ...