Executing AJAX to run JavaScript code

My website utilizes pushState for page loading. I am facing an issue where I want to incorporate JavaScript on a specific page, but the content is loaded via AJAX which prevents the script from functioning as intended. How can I resolve this situation? I have heard about something called "parseScript" but I haven't been able to locate sufficient information on it.

--Sample--

Content loaded through AJAX: Within my page, I include the following script:

<script type="text/javascript">
        function go(){
            alert('1');
        }
    </script>
<a href="javascript:void();" onClick="go();">GO!!!</a>

However, nothing occurs when clicked.

--Update--

If I inspect using Google Chrome's debugger: "Uncaught ReferenceError: go is not defined" Additionally, the <script> tag cannot be located anywhere in the code.

Answer №1

Web browsers may not interpret the content of a <script> element if it is added to the document using targetElement.innerHTML. This could be the issue you are facing.

A recommended solution would be to utilize a reliable framework like jQuery for handling such situations. Frameworks like jQuery have already addressed the challenges of injecting scripts into the DOM safely and efficiently. It's usually best to leverage existing solutions rather than reinventing the wheel, unless minimizing library dependencies is crucial for your project's requirements.


An alternative approach to solving this problem is to separate the JavaScript code from the HTML content in the response obtained via Ajax. This can be achieved by making two separate requests (although this might impact performance) or by structuring the JavaScript and HTML within a JSON object (which could potentially complicate maintenance).

Below is an example implementation:

<script>

function load_content(){
  var req = new XMLHttpRequest();
  req.open("GET", "ajax.json", true);
  req.onreadystatechange = function (e){
    if (req.readyState === 4){
      if (req.status === 200){

        // Injecting JavaScript and HTML content into the DOM
        var json = JSON.parse(req.responseText);
        document.getElementById("target").innerHTML = json.html;
        eval(json.js);
      } else {
        console.log("Error", req.statusText);
      }
    }
  };
  req.send(null);
}

</script>

<a href="#" onclick="load_content()">Load more stuff</a>
<div id="target"></div>

The content of the document ajax.json hosted on the server should resemble the following structure:

{
  "js": "window.bar = function (){ console.log(\"bar\"); return false; }",
  "html": "<p><a href=\"#\" onclick=\"bar();\">Log a message</a></p>"
}

If you opt for this method, remember to either:

  • namespace your functions: MyApp.foo = function (){ ... };, or
  • explicitly add your functions to the global namespace: window.foo = function (){ ... };.

This caution is due to the fact that the use of eval executes within the current scope, causing potential scoping issues with function availability. In the provided example, the latter option was chosen for simplicity, but understanding this distinction is crucial for successful implementation.

Before proceeding with this approach, it is highly recommended to review the article on When is JavaScript's eval() not evil? to ensure safe and appropriate usage of eval().

Answer №2

In order to improve clarity, it would be beneficial to include more information on the process of making an Ajax call and loading content. Here are a few key points to consider:

  • The correct syntax for javascript:void() should be javascript:void(0). Additionally, using javascript:void() in the href attribute of an anchor tag is not recommended as some browsers do not support it. If you must use an anchor tag, set the href to # and add "return false;" to the click event.
  • It would be better to use a button tag instead of an anchor tag in this scenario.
  • Based on the information provided, the code should work (excluding the syntax error with void())

Answer №3

To achieve this task, my approach would involve utilizing jQuery's load function. This allows for handling an ajax request and extracting script or no-script elements.

If you prefer not to rely on jQuery, I recommend researching the functionality of the load method and incorporating it as an event handler in your ajax implementation.

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

Unraveling the JSON section within a intricate text document

Embarking on the development of a desktop application using Electron, I aim to parse files and present data extracted from these complex files. These files contain intricate information. My current challenge involves extracting JSON data from a convoluted ...

React Hook is failing to trigger an update

Learning React and JavaScript has been quite a challenge for me, especially when it comes to understanding React Hooks and the issue of them not updating sometimes. I have tried searching online but either end up with solutions for class-based components o ...

Unraveling the complexities of parsing multi-tiered JSON structures

I am struggling with indexing values from a multi-level JSON array. Here is the JSON data in question: { "items": [ { "snippet": { "title": "YouTube Developers Live: Embedded Web Player Customization" } ...

Issues arise when attempting to use JavaScript to update the innerHTML content of a webpage

I have created a JavaScript code (shown below): function gup(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex ...

How to Make a Div Tag Fade Effect with JavaScript in an External File

*** New Team Member Notice *** I'm currently working on an assignment and trying to implement a simple fade effect on a box. While it seems like this should be straightforward, I'm encountering some obstacles. Currently, the button causes the bo ...

How to update a deeply nested object within a mongoose document

I've been struggling to update a specific object within a Mongodb document using the findOneAndUpdate() method. Here is a snippet of my collection structure: { _id: new ObjectId("61da0ab855483312e8f4483b"), products: [ { creat ...

In need of an AJAX image viewer compatible with PHP or considering transforming an ASP image viewer to PHP

Currently, I am in search of a Javascript (preferably based on jQuery) Ajax image viewer with a zoom feature that is compatible with PHP. The closest match to what I require is a script called "thinDoc" which I found to be very impressive: thinDoc To se ...

Is it possible in HTML to create an "intelligent" overflow effect where text is truncated and replaced with an ellipsis "..." followed by a link to view the full content?

I have a <div> that has a limited size, and I am looking for a way to display multiline text in it. If the text exceeds the available space, I would like to add "..." at the end along with a link to view the full content on another page. Is there a ...

Converting JSON data from ASP.NET MVC to a Canvas.js chart

Despite my efforts to find a solution by looking through similar posts, I am unable to resolve the issue. Within my asp.net MVC controller, I have a method called public object OfferChart() List<Det> obj = new List<Det>(); foreach ...

Angular Display of Scrolling Feature not Functioning Properly

After clicking on show5 and then goto5, everything functions as expected. However, when clicking on showngo5, it does not work as anticipated, despite the fact that the same methods are being called. What is causing showngo5 to not work in this plunker h ...

Create dropdown options from JSON data

I'm attempting to populate a dropdown menu using a JSON response retrieved from an API. let dropdown = $('#LA_picker'); dropdown.empty(); dropdown.append('<option selected="true" disabled>Choose State/Province</option>& ...

Dynamic jquery panel that remains expanded while concealing the menu on large screens

The page demonstrating jquery features automatically opens a side panel on large screens and displays a logo image instead of the standard 'open panel' icon. It remains open until the screen size is reduced. Take a look at the demonstration here: ...

Modifying selections within a select box generated dynamically using JQuery

Looking for help on how to delegate to a static DOM element in my current situation. I need to create a dynamic select box .userDrop when .addNew is clicked, and then have the user select an option from #secDrop, triggering a change event that calls the da ...

ng2-idle server side rendering problem - Uncaught ReferenceError: document is undefined

Can ng2-idle be used for idle timeout/keepalive with pre-rendering in Angular 4? I followed this link for implementation: It works fine without server pre-rendering, but when I add rendering back to my index.html, I keep getting the following error: Exce ...

What is the best way to configure redux-sagas and organize file hierarchy?

After learning how to install JWT and apply it to my React Native project, I realized that without proper state management, I had to pass the JWT token fetched from the login authentication as props down multiple levels, which became quite cumbersome. This ...

The deletion function necessitates a switch from a server component to a client component

I built an app using Next.js v13.4. Within the app, there is a server component where I fetch all users from the database and display them in individual cards. My goal is to add a delete button to each card, but whenever I try to attach an event listener t ...

Dynamic Filtering with Reactjs Autocomplete Component (Material UI) using API calls on each input modification

Just starting out with Reactjs and looking to build an Autocomplete component that fetches API data on every input change to update the options. I've been using the Autocomplete component from Material UI but struggling to get it working as expected. ...

Using CoffeeScript to Invoke Methods

I'm still learning CoffeeScript and encountering some challenges with calling methods. Can someone help me out? Here is the Card model I am working with: class exports.Card extends Backbone.Model defaults: pip: '4' suit: &apos ...

Launching a URL in a pop-up window with customized title and address bar

I am seeking to implement a feature similar to the following: <a href="post/23">post 23</a> When a user clicks on this element, I want a popup div to fade in and load the HTML from page post/23 into it. Additionally, I would like the title an ...

Struggling to extract text from within a <p> tag on an Ionic 1 app page on iOS

After developing an ionic-1 application for iOS and Android devices, I encountered an issue with displaying mobile numbers in one of the views. The numbers are contained within <p> tags. While users can click and hold on a number to copy it on Andr ...