An AJAX script that performs the following sequence of actions:
- Creates a hidden iframe to buffer server-side output
- Loads PHP content silently into a div using the iframe
- 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>