The JSONP request connected to the user input field and button will only trigger a single time

Hello all, I'm new to this and have been searching the internet high and low to see if anyone has encountered a similar issue before, but haven't had any luck.

I've been attempting to set up a JSONP request to Wikipedia that is connected to a user input field on my webpage. This request should be triggered by a button click in a search field. Everything works smoothly the first time it's used after the page loads (returns the numerical page id), but subsequent searches don't update the response variable...

Thank you in advance for your assistance!

P.S. - I'd prefer to avoid using jQuery if possible and stick with pure JS, thank you.

Find the code below:

var x = document.getElementById("test");
var y = document.getElementById("loadResults");
var wikiResponse;
var script = document.createElement("script");
var userInput;

function launchSearch () {
  if (document.body.contains(script)) {
    document.body.removeChild(script);
  }
  script.src = "https://en.wikipedia.org/w/api.php?action=query&titles=" + userInput + "&prop=revisions&rvprop=content&indexpageids=1&format=json&callback=loadResults"; 
  document.body.appendChild(script);
}

function loadResults(response) {
 wikiResponse = response.query.pageids[0];
 x.textContent = wikiResponse;
}

y.addEventListener("click", function() {
  userInput = document.getElementById("userInput").value;
  launchSearch();
});

Answer №1

If you want your script to be executed, make sure to create it using the createElement method. Simply removing it from the body and then adding it again with appendChild will not trigger its execution (refer to this response).

To ensure your script runs as intended, consider creating the element with createElement each time you need to load it instead of manipulating its presence in the DOM.

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

Unable to close Bootstrap modal upon clicking "x" or "close" buttons

Hey everyone, I'm having a bit of trouble with my modal. It appears correctly when clicked to open, and the close buttons seem to detect that my mouse is hovering over them. However, when I click on the buttons, nothing happens and the modal remains o ...

Executing npm commands programmatically from a node.js script

Currently, I am developing a specialized command line interface (CLI) for managing various packages to be installed or uninstalled using npm. Should I execute npm through spawn('npm') or require('npm')? require('child_process&apos ...

NextJS middleware API receives an uploaded image file form, but the request is undefined

Currently, I'm utilizing NextJS to handle form data processing and database uploads, with a pit stop at the NextJS API middleware for image editing. pages/uploadImage.tsx This is the client-side code handler. ... async function handleImageUpload(imag ...

Utilizing predicates in JSON: A guide

Currently, I am diving into iOS development and looking to implement a SearchBar along with a SearchDisplay Controller in my RootViewController. My goal is to display expressions from a JSON URL in the SearchBar. However, I'm encountering challenges w ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

Breaking apart a string and mapping it to specific fields

My issue is relatively straightforward. Upon loading my page, a long string representing an address is generated. For example: 101, Dalmations Avenue, Miami, Florida, USA, 908343 With the help of jQuery, I can split the string using: var address = sel.o ...

I am noticing that my popover is causing my page to shift when I click it. It is expanding the width of my page more than I would

Upon clicking the user id popover on my page, it expands the page width instead of adjusting within the page boundaries. This is the issue: https://i.stack.imgur.com/EqaMo.png There's a small white space present that I want to eliminate. When the po ...

Jackson refuses to name fields according to my preferences

Similar Issue: Handling JSON Property Names During Serialization and Deserialization On my website, I am utilizing Jackson library to generate an options string for a charting tool that requires JSON input. For instance, I have a public class Chart ...

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

The Intersection Observer API is not compatible with using transform: translateX()

After successfully implementing the Intersection Observer API on my website and incorporating a few transitions from an example I came across, everything seemed to be working smoothly. You can view the scale-in transition in action here: https://jsfiddle.n ...

I wonder what the response would be to this particular inquiry

I recently had an angular interview and encountered this question. The interviewer inquired about the meaning of the following code snippet in Angular: code; <app-main [type]="text"></app-main> ...

Triggering jQuery events can be customized by excluding certain elements using the

Is there a way to hide the div "popu" when clicking on the img "tri"? I've tried using .not() since the img is a child of the div popu, but it didn't work. Also, I need to make sure that clicking on the div "textb" does not trigger the hide actio ...

Enhance your React application by making two API requests in

Below is the React Component that I am working on: export default function Header () { const { isSessionActive, isMenuOpen, isProfileMenuOpen, setIsMenuOpen, closeMenu, URL } = useContext(AppContext) const [profileData, setProfileData] = useState({}) ...

conceal specific language options within the dropdown selection box

In my user interface, I have implemented a drop-down menu that allows users to select their preferred language. I want the selected language option to disappear from the drop-down menu once chosen. Here is the HTML code snippet: <li> < ...

Submitting form based on HTML select input issue

I am facing an issue with a select form where the value resets to "10" every time I send the form. Is there a way to keep the selected option, for example "20", after submitting the form? Below is the code snippet: <form method='get' name=&a ...

How can I include additional view folders for Jade files in my EXPRESS application?

So, I understand that by using app.set('views', path.join(__dirname, 'views')); in Express, the view variable is set to render all .jade files in the ./views folder. However, I'm wondering if there's a way to add additional p ...

The property is not found within the type, yet the property does indeed exist

I'm baffled by the error being thrown by TypeScript interface SendMessageAction { type: 1; } interface DeleteMessageAction { type: 2; idBlock:string; } type ChatActionTypes = SendMessageAction | DeleteMessageAction; const CounterReduc ...

Troubleshooting issue: Django and Javascript - Why is my dependent dropdown feature not

I am new to using a combination of Javascript and Django. Below is the script I have written: <script> $(document).ready(function() { $("#source").change(function() { var el = $(this); var reg = ...

Why is my "webpack" version "^5.70.0" having trouble processing jpg files?

Having trouble loading a jpg file on the Homepage of my app: import cad from './CAD/untitled.106.jpg' Encountering this error message repeatedly: assets by status 2 MiB [cached] 1 asset cached modules 2.41 MiB (javascript) 937 bytes (rjavascript ...

Update the JSON by replacing any null values with a predefined string

When working with JSON data, I often come across empty values that I need to replace with a default string. var jsonData= [ { "machineNum": "1A", "serialNo": "123", "city": "" }, { "machineNum": "2B", "serialNo": "", "city": "" }, ...