The AJAX response did not include the <script> element

Currently working on a WordPress theme where I am implementing AJAX to load new archive pages. However, encountering an issue where the entire block of Javascript code is not being included in the newly fetched content.

Let's say, initially the structure looks like this :

<div id="post-1">
    <script type="text/javascript">
    //some codes here//
    </script>

    <div class="content">
    </div>
</div>

But after navigating to the next page and back using AJAX, the returned content doesn't include the script section as shown in Firebug :

<div id="post-1">
    <div class="content">
    </div>
</div>

The Javascript codes are still visible under the 'Inline' script in the 'Script' tab of Firebug, but missing from the actual content.

Looking for guidance on what could be causing this glitch in fetching new content via AJAX? Below is the snippet of code being utilized:

    jQuery('.ajax-pagination a').live('click', function(e){ //capture click event on pagination link
    e.preventDefault();
    var link = jQuery(this).attr('href'); //Get the href attribute
    jQuery.ajax({
        url: link,
        dataType: "text",
        context: document.body,
        beforeSend: function(){jQuery('#container').fadeOut(500)},
        success: function(html) {
            var newhtml = $('#container', $(html))
            $('#container').html(newhtml);
            $("container").find("script").each(function(i) {
                eval($(this).text());
            });
            jQuery('#container').fadeIn(500);

        },
        error: function() {
            alert('Error');
        }
    });
    });

Attempting to execute the loaded Javascript content through AJAX, however, it seems like the Javascript itself isn't getting included along with the other content.

Appreciate your time in going through the detailed query, any assistance would be immensely valuable!

Answer №1

The method .html() removes any <script> tags that are included in the inserted HTML content.

Prior to inserting the HTML, you must traverse through it to identify all script tags and then utilize jQuery.globalEval to execute their scripts.

success: function(html) {
    var newContent = $('#container', $(html));

    // executing script tags - assuming they are inline
    $('script', newContent).each(function() {
        $.globalEval($(this).text());
    });

    $('#container').html(newContent).fadeIn(500);
}

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

Refresh the navigation bar on vuejs post-login

Creating a client login using Vue has been a challenge for me. My main component includes the navigation bar and the content rendering component. The navigation component checks if the user is logged in to display the buttons for guests and hide the button ...

Updating the parent's reference from a child component in Vue 3

In one of my child components, I have a component named Navbar that includes an option for logging out. <a @click="(event) => {event.preventDefault();}"> Logout </a> This Navbar component has been imported into my parent compon ...

Sending data from frontend to backend in a Node.js Express application

My Node.js Express project in the WebStorm IDE is structured like this: https://i.sstatic.net/pQKwb.jpg I'm trying to find a way to pass a variable from index.js to app.js so that I can write it to data.json at the end. As a beginner in Node.js, I& ...

Customize the duration of Skeleton animations in Material UI

The <Skeleton> components in mui utilize pulse or wavy animations. Wondering if there's a method to quicken this animation, perhaps by adjusting the duration? ...

Using jQuery to send JSON data through AJAX to PHP

I'm attempting to utilize jQuery AJAX to send JSON data to a PHP file. My goal is to extract the values and IDs from multiple child elements, create a JSON object with this data, and then transmit that object to a PHP file for processing and insertion ...

Expanding the MatBottomSheet's Width: A Guide

The CSS provided above is specifically for increasing the height of an element, but not its width: .mat-bottom-sheet-container { min-height: 100vh; min-width: 100vw; margin-top: 80px; } Does anyone have a solution for expanding the width of MatBott ...

Employing lodash for object comparison and removal from an array

In my current project, I am using lodash to compare two arrays of objects and extract the differences between them. The goal is to add this difference to the original data set while maintaining the existing data intact. For instance, if there are initially ...

How can getters in vuex be utilized uniquely?

After dedicating two weeks to studying Vuex, I find myself pondering the true significance and purpose of getters in the framework. I ran the following code snippet and everything seems to be functioning properly. this.$store.getters["app/url"] ...

Delay fading in during the loading process

Recently, I came across a neat animation effect that I would love to incorporate into an upcoming project. The effect involves animating the opacity on load, also known as a fade in. I am curious if it is possible to link multiple elements together (for ...

Struggling to Interpret JSON Data

I am currently working on updating the content of a mobile version of a desktop site by using an Ajax call back to the desktop version. The mobile site is located on a separate subdomain, and I am retrieving page content from the desktop version in JSON fo ...

Adding plain HTML using jQuery can be done using the `.after()` and `.before()` methods

I have encountered a situation where I need to insert closing tags before an HTML element and then reopen it with the proper tags. The code snippet I am using is as follows: tag.before("</div></div>"); and then re-open it by adding proper tag ...

The "keydown" event in React will not alter the state

I am currently developing an application that requires me to track the keys pressed by the user. I am utilizing keydown and keyup events for this purpose. However, I am facing a challenge where I do not want the same key to be registered multiple times whe ...

Dealing with Unwanted Keys When Parsing JSON Objects

Struggling with parsing a list of Objects, for example: After running the code JSON.parse("[{},{},{},{},{}]"); The result is as follows: 0: Object 1: Object 2: Object 3: Object 4: Object 5: Object Expecting an array of 5 objects like this: [Object,Ob ...

issue with useReducer not functioning as expected

I encountered an issue with my customized Select component. It includes a select and options while listening for onChange events. Additionally, I am using a useReducer function that initializes some variables. However, even after selecting an option, the s ...

javascript Try again with async await

I am working with multiple asynchronous functions that send requests to a server. If an error occurs, they catch it and retry the function. These functions depend on data from the previous one, so they need to be executed sequentially. The issue I am facin ...

What Causes the Response to Vary in a Post Request?

Issue: When I use console.log(res.data), it shows different data compared to console.log(JSON.parse(res.request.response)). My Next.js application is sending a post request to an internal API. The response from the REST endpoint should contain a list obje ...

The hamburger menu unexpectedly appears outside the visible screen area and then reappears at random intervals

My website has a hamburger menu for mobile devices, but there's a problem. When the page loads on a small screen, the hamburger menu is off to the right, causing side scrolling issues and white space. I thought it might be a CSS problem, but after exp ...

How can JSON data be passed to the Google Charts API?

I am currently working on a project that involves retrieving JSON data from a website and visualizing it on a live graph using the Google Charts API. Despite my efforts, I am unable to get the chart to display properly. Can someone please guide me in the r ...

Guide on embedding PHP/MYSQL array into an independent JavaScript document

I'm looking for guidance on how to insert an array from a PHP MySQL page into a separate JavaScript file. Can someone please help me with indicating where to include the PHP URL and provide the correct format for the PHP array code in order to achieve ...

Fill in a data table beginning with the column next to the first

My issue involves a datatable retrieving JSON data from an API. The table is configured so that the first column should only display a checkbox. However, upon data retrieval, the first column gets populated as well. https://i.sstatic.net/izb5B.png $.getJ ...