Warning using FetchContent JavaScript

I have been attempting to create an alert for the "save" button after it is clicked, but so far I have not been successful.

Perfil.html

  • Profile.html is not the main page. It is part of a dashboard.
<li class="nav-item">
  <a class="nav-link" href="#" a-view="infoPessoal" onclick="fetchContent(this)" a-folder="administrativo">
    <i class="fas fa-info-circle"></i>
    <!-- Icons -->
    Information
  </a>
</li>

<div class="ajax-fullscreenperfil" id="ajax-fullscreenperfilJs">
   <p></p>
</div>
<script>
  let button2 = document.querySelector('form button.btn')
  button2.addEventListener('click', () => {
      alert("Handler for .click() called.")
  })
</script>

Ajax.js

  • I used to make the html call on the same page that is the nav-bar.
let content = document.getElementById('ajax-fullscreenperfilJs')

function fetchContent(el) {
    let view = el.getAttribute('a-view')
    let folder = el.getAttribute('a-folder')
    fetch(`../ajax/${folder}/${view}.html`)
        .then(response => {
            let html = response.text()
            return html
        })
        .then(html => {
            console.log(html)
            content.innerHTML = html
        })

}

InfoPessoal.html

  • This is the page that will be shown in the prof.html div.
<div class="main-content">
    <div class="perfil-parent">
        <div class="perfil">
            <div class="perfil-img">
                <div class="img">

                </div>
            </div>
            <div class="perfil-form">
                <form>
                    <div class="form-group">
                        <label for="name">Full Name:</label>
                        <input type="text" class="form-control" id="name" placeholder="Enter your full name.">
                    </div>
                    <div class="form-group">
                        <label for="email">Email:</label>
                        <input type="email" class="form-control" id="email" placeholder="Enter your email.">
                    </div>
                    <div class="form-group">
                        <label for="age">Age:</label>
                        <input type="text" class="form-control" id="age" placeholder="Enter your age.">
                    </div>
                    <div class="form-group">
                        <label for="corp">Institution:</label>
                        <input type="text" class="form-control" id="corp" placeholder="Enter your institution or company.">
                    </div>
                    <div class="form-group">
                        <label for="genre">Access Priority:</label>
                        <select class="form-control" id="genre">
                          <option>Client</option>
                          <option>Maintenance</option>
                          <option>Administrator</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="password">Password:</label>
                        <input type="password" class="form-control" id="password" placeholder="Enter your password.">
                    </div>
                    <div class="custom-file">
                        <input type="file" class="custom-file-input" id="customFile">
                        <label class="custom-file-label" for="customFile">Choose photo</label>
                    </div>

                    <button type="button" class="btn">Save</button>
                </form>
            </div>
        </div>
    </div>
</div>

I am able to successfully load the infoPersonal.html view through Ajax, but I am unable to trigger an alert by clicking on the "Save" button.

Answer №1

It seems like the issue arises when running the code below before receiving the AJAX response. This results in attempting to select DOM elements that have not been created yet.

  let button2 = document.querySelector('form button.btn')
  button2.addEventListener('click', () => {
      alert("Handler for .click() called.")
  })

To solve this, you can encapsulate the above code within a function and call that function upon receiving the fetch response.

function alertFunc() {
  let button2 = document.querySelector('form button.btn')
  button2.addEventListener('click', () => {
      alert("Handler for .click() called.")
  })
}

function fetchContent(el) {
    let view = el.getAttribute('a-view')
    let folder = el.getAttribute('a-folder')
    fetch(`../ajax/${folder}/${view}.html`)
        .then(response => {
            let html = response.text()
            return html
        })
        .then(html => {
            console.log(html)
            content.innerHTML = html
            alertFunc()  //   <-----  fire it 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

Procedure for distributing proportions

Imagine having an object like this: const data = { bills: 10, rent: 40, food: 50, } The total is 100 (or 100%). If we update the bills to a value of 20, the other properties should adjust accordingly, for example: { bills: 20, re ...

Tips for setting up a bookmark in bootstrapvue

Hello everyone, I am currently working with bootstrapvue and I need help figuring out how to add a favorite icon. The documentation only provides icons for rating systems. I have a list of reports and I want users to be able to mark their favorites, simil ...

Displaying a two-dimensional array from a JSON file using AngularJS ng-repeat

Looking at this HTML file, I am trying to display a 2D array from the json-$scope.listOfIngredient <div class="ingredientMapping" ng-repeat="IngredientMapping in listOfIngredient track by $index"> <ul> <!-- BEGIN: Inner ngRep ...

Tips for refreshing the direction route in google-maps-react

I have an array of coordinates, and when I add a new coordinate to the array, I want the route direction on the map to update accordingly. This is the code snippet from my googlemap.js file: /* global google */ import React, { Component } from "react ...

The function 'ChartModule' cannot be called, as function calls are not supported

I am encountering a similar problem as discussed in Angular 2 - AOT - Calling function 'ChartModule', function calls not supported ERROR: Error encountered while resolving symbol values statically. Trying to call function 'ChartModule&apos ...

What is the best way to pass a prop into the <router-link>?

If I replace this {{ name }}, the result is "campaigns" Now, I want to use that in my link <router-link :to="'/' + '123' + '/' + item.id"> {{ item.name }}</router-link> I attempted to substitute '1 ...

Tips for fixing the issue of disappearing top margins in elements while using CSS3 Pie in Internet Explorer 7

Hey there! I've been experimenting with a lot of CSS3 effects, but I'm running into issues trying to get the same effects to work on IE 7 and 8. I've been attempting to use CSS3 Pie to help with this. While CSS3 Pie has worked well for som ...

What methods can I implement to ensure a button illuminates only when correct information is provided?

I have developed a calculator for permutations and combinations. When either permutation or combination is selected, and the required values are entered, I want the calculate button to light up. How can I achieve this without using setInterval in my curren ...

How can I showcase the index of `<tr>` and `<td>` elements in a dynamically generated table

How can I print the index of table rows and data on click in javascript? <html> <head> <title>Table Creation</title> <script language="javascript" type="text/javascript"> function createTable() { ...

Output the values of jQuery variables into PHP

Within the same php file, I am storing two variables using this script and I want to be able to print both using php $('#table tbody').on( 'click', 'td', function () { var row = $(this).parent().find('td').h ...

What is the best way to consolidate multiple JS files into one main file that I can easily reference in my HTML code?

I've dedicated countless hours to watching videos and compiling a comprehensive library of assets, similar to p5.js (I'm especially fond of Dan Shiffman's content). I now have numerous files for various functions - init.js, dom.js, drawing.j ...

What is the best way to shorten string values that exceed a certain length?

Here is an array list I have: $myarray = array( array( 'name' => 'File name 1 - type.zip', 'size' => '600KB', ), array( 'name' => 'File name 2 - type.pdf&a ...

Unable to successfully Uploading an Image using PHP

I've encountered a new issue. I'm trying to upload an image from my webpage into a folder on the server (using XAMPP). Despite trying multiple examples, including those from php.net and w3schools.com, the code isn't working and I can't ...

Challenges compiling 'vue-loader' in Webpack caused by '@vue/compiler-sfc' issues

The Challenge Embarking on the development of a new application, we decided to implement a GULP and Webpack pipeline for compiling SCSS, Vue 3, and Typescript files. However, my recent endeavors have been consumed by a perplexing dilemma. Every time I add ...

Elements in the rCharts flow chart

I have implemented the code below to create an rCharts Sankey diagram, sourced from https://github.com/timelyportfolio/rCharts_d3_sankey: if(!require(rCharts)){ library(devtools) install_github('ramnathv/rCharts') } library(rCharts) sankeyP ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

async.auto: halt the entire sequence upon encountering the initial error

My understanding was that the behavior of async.auto was such that if one task returned an error (err), the global callback would be triggered with this error and no further tasks would execute. It seemed logical - why continue executing tasks when an erro ...

Dynamically load an external JavaScript file based on the presence or absence of specific elements on the webpage

Hi there, I have a question for you all. Situation: We are using a javascript tool to conduct A/B testing on our landing page designs. I want version A (control) to be linked to one external javascript file, while version B (variation) is linked to a diff ...

Calculating the sum of all textboxes with jQuery

I'm encountering an issue when trying to add the values of textboxes on blur call. Specifically, after entering a number in one of the textboxes, it throws NaN when attempting to sum up the values from other textboxes. Below is the code snippet causi ...

Unlock the power of jQuery chaining with the val() method

My selected background color is set to: var _back = "#FF0000"; Why doesn't this code change the input field's background color: $("#input").val( _back ).css("background-color",$(this).val()); But this one does? $("#input").val( _back ) ...