Note that there are some explanatory texts on larger screens.

plurals
  1. POsimple iframe based AJAX script: first call yields 'null' element, subsequent call's work perfect. What am I not understanding here?
    primarykey
    data
    text
    <p>Very simple AJAX script that does the following:</p> <ol> <li>inserts hidden iframe for buffering server side output</li> <li>iframe loads my PHP content silently into a div</li> <li>PHP output is copied from server side div, to parent page div.</li> </ol> <p>The problem is, the first call throws : 'Uncaught TypeError: Cannot set property 'src' of null'. All subsequent calls work perfectly. It's driving me nuts. I love the simplicity of this function but I'm obviously missing something.</p> <p><strong>Javascript called from here:</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;!-- ajax --&gt; &lt;script src='ajax.js' type='text/javascript'&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a href='#' onClick="ajax_request('php.php','show_result');return false;"&gt;get ajax data&lt;/a&gt; &lt;div id='show_result'&gt;&lt;/div&gt; &lt;body&gt; &lt;/html&gt; </code></pre> <p><strong>'ajax.js' file :</strong></p> <pre><code>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 it's not created already. 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; // get 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 result document.getElementById(result_id).innerHTML = content_to_transfer; } </code></pre> <p><strong>'php.php' server script that outputs the result for transfer via AJAX (random number)</strong></p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div id='to_transfer'&gt;&lt;?=mt_rand(5, 15);?&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload