Executing javascript code that has been inserted into inner HTML is not functioning as expected

Trying to retrieve a response from another page, specifically named ajaxresponse.php, through an AJAX request. I also aim to execute some JavaScript actions on that ajaxresponse.php page, but the JavaScript code is not functioning as expected. Although I am receiving the response from the page, the JavaScript code on that page is not working. The main query is why the AJAX code on my second page is not operational?

function ajaxinput(tinnerid)
{
    var xmllhttp;
       if (window.XMLHttpRequest)
        {
          xmlhttp=new XMLHttpRequest();
        }
       else
        {
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
       xmlhttp.onreadystatechange=function()
        {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
           {
            document.getElementById("articledive").innerHTML=xmlhttp.responseText;
           }
        }
    xmlhttp.open("GET","ajaxresponse.php?q="+tinnerid,true);
    xmlhttp.send();
}

Below is the PHP code for the first page:

<?php
 $con1=mysqli_connect("127.0.0.1","root","root","databasetry");
 $result=mysqli_query($con1,"select title,articleid  from article");
 $tinnerid=0;
 $articledivid=0;
   while($row = mysqli_fetch_array($result))
    {
     $tinnerid=$row['articleid'];
     echo "<div class='tinner' id='$tinnerid' onclick='ajaxinput($tinnerid)'    style='cursor:pointer;'>";
     echo"<span class='fontdiv'>";
     echo $row['title']."<br>";
     echo "</span>";
     echo"</div>";
     $tinnerid++;
     $articledivid++;
    }
 mysqli_close($con1);
?>

Now moving onto the JavaScript code for the second page:

function run()
{
 alert("example");
}

Last but not least, here is the PHP code of the second page:

 <?php
  $id=$_GET['q'];
  $result=mysqli_query($con1,"select user.username,article.articleid,article.title,article.artiletext from article inner join user on article.user_id=user.user_id where article.articleid=$id");
 $divid=0;
    while($row = mysqli_fetch_array($result))
     {   
      $id=0; 
      echo"<div class='inner' id=$divid >";
      $id=$row['articleid'];
      echo "<font class='ftitle'>"."Title : "."<a href='#'onclick='ajaxinput($id)'>".$row['title']."</a>"."</font>"."<br>"."<font class='ftext'>".$row['artiletext']."</font>"."<br>"."<font class='flast'>"."Posted By : ".$row['username']."</br>"."</font>"."<br>"."<br>";    
      echo "<button type='button' onclick='con($id)'  class='button'><font size='1'>Delete</font></button>";
      echo"</div>";
      $divid++;
      echo"<script>run()</script>";   
      }
  mysqli_close($con1);
 ?>

Answer №1

When inserting JavaScript as innerHTML at runtime, it may not be executed. One solution is to eliminate the script tag from the second page return, and then invoke the run() method on the first page following the ajax callback. Here's an example:

function ajaxinput(tinnerid)
{
   var xmllhttp;
   if (window.XMLHttpRequest)
    {
      xmlhttp=new XMLHttpRequest();
    }
   else
    {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
   xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
        document.getElementById("articledive").innerHTML=xmlhttp.responseText;

        /* CALL IT HERE AFTER INSERT */
        run();
       }
    }
xmlhttp.open("GET","ajaxresponse.php?q="+tinnerid,true);
xmlhttp.send();

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

Change the icon switch from fas fa-lock-open to fas fa-lock by adding an event listener for a click action

let lockIcon = document.createElement("i"); lockIcon.setAttribute("class", "fas fa-lock-open"); lockIcon.setAttribute("id", color + "lock"); Is there a way to toggle between the icons fas fa-lock-open and fas fa-lock when clicking using a ...

The integration of Vue JS is not displaying properly in an Electron application

My electron app is loading Vue JS 2 from my local machine, but when I attach my el to an element, it completely empties the element and replaces its contents with a Vue JS comment. What could be causing this issue? index.html <!DOCTYPE html> <htm ...

In what location can event listeners be found in npm packages?

For a while now, I've been immersed in the world of coding as I work on creating my very own IRC bot using nodejs. This project serves as an invaluable learning experience for me, and as I navigate through the process, I constantly encounter event lis ...

Unlawful use of the return statement

Can you identify the issue with this code? The browser reports: "Uncaught SyntaxError: Illegal return statement" I'm looking for an explanation in this format: 1 2 3fool 4 5bar 6fool 7 8 9bar... let arr = []; for (i = 0; i <= 100; i++) { if ( ...

I am experiencing an issue where the Axios configuration does not display the OnUploadProgress on my response

I have been attempting to track the progress of file uploads from the front end, but I am encountering an issue where the onUploadProgress is not being received in the configuration catch. This problem arises as I am relatively new to using Axios. axios({ ...

Updating the src of an iframe and adding an onclick event to a link using JavaScript

Looking to design a page that accommodates both login and sign up functionalities by dynamically updating the src of an iframe. In the navigation bar, there is: <li id="change"><a onclick="sign()">Sign up</a></li> And within the ...

Using 'if' conditions in Reactjs: A step-by-step guide

Working with Reactjs in the nextjs framework, I have received user data that includes the "category name (cat_name)" selected by the user. Now, I need to display that category in a dropdown menu. How can I achieve this? The current code snippet showcases ...

Prevent time slots from being selected based on the current hour using JavaScript

I need to create a function that will disable previous timeslots based on the current hour. For example, if it is 1PM, I want all timeslots before 1PM to be disabled. Here is the HTML code: <div class=" col-sm-4 col-md-4 col-lg-4"> <md ...

Guide to testing express Router routes with unit tests

I recently started learning Node and Express and I'm in the process of writing unit tests for my routes/controllers. To keep things organized, I've split my routes and controllers into separate files. How should I approach testing my routes? con ...

The Django implementation is returning a null response when handling an Ajax request

I am currently working on a Django web application and I am facing an issue with making an ajax call to upload a large image. The goal is to upload the image, then process it using the pythonocc library to retrieve volume information. Due to the time-consu ...

Retrieving information from a datatable in vb.net with an array

Working on a chart using highcharts with code behind in vb.net... I have a datatable structured like this: Date - speed - data 2011 10k 6 2011 18k 7 2012 20k 10 2012 10k 2 2013 14k 4 2013 20k 6 Previously, to ...

Exploring the Spotify API with jQuery/ajax to fetch details about songs, artists, and albums

I've been researching and have come across some information that is somewhat similar, but I'm still struggling to completely understand how this process works. My goal is to make a request to the Spotify API using jQuery to search for an artist ...

Displaying elapsed time in JavaScript (Node.js)

Looking for a way to convert a date time or time-stamp format like 2015-12-18 07:10:54 into a relative time, such as "2 hours ago." I attempted the code provided, but it seems to consistently show an incorrect estimation of "8 days ago." function convert ...

Discover how to prevent a link or text from appearing if a user has already browsed a particular webpage

Is there a way to hide a link to another page if the user has previously visited that page? For example, I have 3 options - A, B, and C. If a user selects option A, links to pages B and C are displayed at the bottom of the page. However, if they then navi ...

The Jssor bullet navigator is not visible on the webpage

Currently, I am working on implementing a full-width slider with arrow navigators, bullet navigators, and captions using the Jssor plugin. Rather than copying and pasting example code, I decided to tackle this project independently with just a little guida ...

Transform a JSON array with keys and values into a structured tabular format in JSON

Looking to transform the JSON data below for a Chart into a format suitable for an HTML table: var chartJson = [ { header : '2016', values : [1, 5, 9] }, { header : '2017', values : [2, 4, 8] ...

Equivalent of ResolveUrl for loading scripts without the need for server technology

I am in the process of converting an ASP.NET web page into a plain HTML web page. Most of the work is done, however, I am having trouble replacing the ASP.NET Page.ResolveUrl function when setting a reference to a javascript file: <script src="<%= ...

React: What is the best way to dynamically render images by iterating through a list?

Currently, I am attempting to iterate through an array of objects. Each object within the staff array in my JSON contains an imgUrl: { "home": { ... "staff": [ { ... "imgUrl": "../Images/Jon ...

What is the proper method to transmit Firebase authentication tokens to a backend server?

I am looking to securely identify the currently signed-in user on my nodejs server. After a successful sign-in, I need to send the user's ID token to the server using HTTPS for verification. Following the guidance in Firebase documentation: firebase ...

Executing JavaScript Function on the Server Side

Recently, I created a JavaScript function that looks like this: function ShowMsg(msg) { $.blockUI({ message: '<div dir=rtl align=center><h1><p>' + msg + '</p></h1></div>', css: { ...