I am having trouble with a basic AJAX script using iframes. The first call returns a null element, but all subsequent calls work perfectly. What am I missing?

An AJAX script that performs the following sequence of actions:

  1. Creates a hidden iframe to buffer server-side output
  2. Loads PHP content silently into a div using the iframe
  3. Copies the PHP output from the server-side div to the parent page div

The issue encountered is during the first call, where it throws an error: 'Uncaught TypeError: Cannot set property 'src' of null'. However, all subsequent calls work perfectly. This bug is causing frustration as I appreciate the simplicity of this function but seem to be missing something crucial.

Javascript code snippet used:

<html>
<head>
    <!-- ajax -->
    <script src='ajax.js' type='text/javascript'></script>
</head> 
    <body>
        <a href='#' onClick="ajax_request('php.php','show_result');return false;">Get AJAX data</a>
        <div id='show_result'></div>
    <body>

</html>

'ajax.js' file contents:

function ajax_request(url,result_id)
{
    var ajax_iframe_id = 'ajax_iframe_loader';
    var ajax_iframe = document.getElementById(ajax_iframe_id);

    // Create hidden iframe transfer buffer if not already created
    if (ajax_iframe == null)
    {

        var element = document.createElement("iframe");
        element.setAttribute('src',url);
        element.setAttribute('id',ajax_iframe_id);
        document.body.appendChild(element);

        element.style.display='none';
        element.style.width='1';
        element.style.height='1';
        element.style.border='0';

        ajax_iframe = element;
    }

    // Load server side page into iframe buffer
    ajax_iframe.src = url;

    // Retrieve the outputted result from inside our transfer div
    var iframe_inner_doc = ajax_iframe.contentDocument || ajax_iframe.contentWindow.document;
    var content_to_transfer = iframe_inner_doc.getElementById('to_transfer').innerHTML;

    // Paste the result
    document.getElementById(result_id).innerHTML = content_to_transfer;

}

'php.php' server script generating random number for AJAX transfer

<html>
<body>
<div id='to_transfer'><?=mt_rand(5, 15);?></div>
</body>
</html>

Answer №1

Make sure to include this code within your conditional statement

ajax_iframe = element;

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

Steps to retrieve the value of a particular row in a table using vuejs

Can you help me retrieve the value of a specific row in a table using VueJS 2? Here is an image of my current table: https://i.sstatic.net/jb1uw.png I need assistance with obtaining and displaying the last value from a loop in the "SHOW QR Button" within ...

Can we enhance this JavaScript setup while still embracing the KISS principle (Keep it simple, Stupid)?

I have completed the following tasks: Ensured all event handlers are placed inside jQuery DOM ready to ensure that all events will only run Defined a var selector at the top of events for caching purposes Please refer to the comments below for what I be ...

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

Is there a way to simulate Pinia and vue-i18n simultaneously?

Exploring Vue 3's Composition API with a twist: The store.ts file import { ref, Ref } from 'vue'; import { defineStore } from 'pinia'; export const useStore = defineStore('store', () => { const isLoading: Ref<bo ...

Strategies for passing a JavaScript variable to a JSP function

I'm dealing with a JavaScript code that has a value stored in its variable that I need to pass to my JSP function. However, I'm facing trouble passing it along. Take a look at the following code snippets: Javascript: $('button').on(& ...

What could be causing the PAGE CSS to malfunction?

I am looking to export HTML text as a word document with A4 size and portrait orientation. My JavaScript currently allows me to export the text, but it appears like a webpage format rather than in A4 or portrait mode. I have tried adding @page CSS styling ...

Advantages of using ConfigService instead of dotenv

What are the benefits and drawbacks of utilizing @NestJS/Config compared to using dotenv for retrieving environment variables? Although I can create a class to manage all envvars in both scenarios, is it necessary? I am aware that @NestJS/Config relies on ...

What could be causing the parameters to be empty in Next.js static site generation with getStaticProps?

Introduction I am currently in the process of developing an application using next.js, specifically utilizing its static site generation feature. Despite following various examples and documentation for hours, I am encountering an issue where the params o ...

navigate to a different section on the page with a series of visuals preceding it

When I try to navigate to a specific dom element on another page, the page initially works fine but then jumps to somewhere before that element. I believe this issue occurs because the page calculates the position before images load, and once the images ar ...

Changing the image source using Javascript and extracting part of the URL

i'm attempting to extract the image url from a series of urls in a loop, removing the hash portion () without the hash (?sqp=-oaymwEjCNACELwBSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLDi79vN15idfFETvntyC9yat7FvZQ). I've managed to mak ...

What is the best method to make a hyperlink within an IFrame open in a new window?

Let me share the code I've been working on: <!DOCTYPE html> <html> <head> <base target="_blank"> </head> <body> <div style="border: 2px solid #D5CC5A; overflow: hidden; margin: 15px auto; max-width: 800px; ...

The React application is functioning properly; however, during compilation, it continually displays an error stating that the module cannot be found

Compilation Failed. Error: Module not found, unable to resolve the specified path. webpack compiled with 1 error I was hoping for a successful compilation, but unfortunately encountered an error. It's perplexing as the application is functioning co ...

The construction of the Gatsby site encountered a major obstacle

I've been facing challenges while trying to build my Gatsby site. Whenever I run 'gatsby develop' in the console, my app starts without any issues. However, when I attempt to build it, I encounter errors like the ones shown below. Does anyon ...

Unable to perform updates for personalized fonts

I've been trying to incorporate custom fonts into my website, but I seem to be facing difficulties in actually implementing them. Could someone please let me know if I am doing it correctly? .pattern{ background:rgba(0,0,0,.5) url(../images/pattern ...

Learn how to effectively declare data as global within Angular2 or Typescript

I am facing an issue with fetching the id inside the Apiservice despite being able to get it in the console. Can anyone provide assistance on how to solve this problem? TS: deleteProduct(index,product) { var token = this.auth.getAccessTokenId(); ...

Incorporate the value of a variable from the .gs file into a personalized HTML sidebar

In my google sheet, I have set up a custom sidebar through scripting. Within this sidebar, I aim to showcase the value from column I in the currently active row. I've successfully created a script that captures and stores the 'I' variable ...

How can you pick the element that is nearest to the top of a window?

My goal is to have a fixed list of page sections on the side that highlights the link of the section you're currently viewing as you scroll through the page. This is the code I've come up with: $(document).scroll(function(){ $allSections = $(&a ...

The straightforward splitting of a string is yielding an object rather than an array

Attempting a simple string split in NodeJS is resulting in an unexpected outcome where it returns an object instead of an array. var mytext = "a,b,c,d,e,f,g,h,i,j,k"; var arr = mytext.split(","); console.log(typeof mytext); <======= output string conso ...

Choose ng-change within the table

I've searched everywhere for an answer to this, but I couldn't find it. I have a table that contains select and date input fields. <table id="tblCorrAction" class="table table-bordered table-striped table-hover table-condensed"> <t ...

Unable to display the Error 404 Component within a nested Component using React Router

When attempting to display the Error component if no matches are found, I encountered an issue - selecting a non-existing route only leads to a blank page. In the example, the Main component adds a sidebar menu and renders all its children inside it. If ...