keep trying function until required DOM element is loaded - javascript

I am loading another page into an el via XHR. The loaded page has js on it that throws an error and fails unless the required dom element is loaded on the page. As it's XHR .ready et. al. won't work.
I have it working with a 500 ms timeout, but that's not OK; there has to be a better way. With timeout, the dom el doesn't always load and the page fails.
There is a table hard-coded on the page with an id. The script in the page is a jquery plugin (datatables) and won't init unless the table is loaded.
I've thought about having a function that inits the datatables stuff and calling that repeatedly while $('#tableID') is null but not sure that's correct.
<div id="contactQueue">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="contactsQueueTable">
<thead>
<tr>
<th class="" rowspan="1" colspan="1" style="width: 185px; ">Contact Name</th>
<th class="" rowspan="1" colspan="1" style="width: 148px; ">Bus. Name</th>
<th class="" rowspan="1" colspan="1" style="width: 116px; ">Is Client</th>
<th class="" rowspan="1" colspan="1" style="width: 165px; ">Remove</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<?php echo form_open('',array('id'=>'step2form','name'=>'step2form'));?>
<input type="hidden" name="clientID" value="<?php echo $clientID; ?>">
<?php echo form_close();?>
<script type="text/javascript" charset="utf-8">
console.log(jq('#currentContactsTable'))
while(jq('#currentContactsTable').html()==null){
initXHRPage();
console.log(jq('#currentContactsTable')+' not ready');
}
function initXHRPage(){
//init tables stuffs
}
EDIT;
The issue was something else, kinda. The script for Datatables is being loaded via getScript(). The element was being loaded normally, but initDatatables() was firing before getScript() was done loading, not before the el was loaded.
The solution was to call the initDatatables() function in the getScript() success callback:
<script type="text/javascript" charset="utf-8">
var jsf = '/js/jquery.dataTables.js';
jq.getScript(jsf, function(data, textStatus){
console.log('Loaded:'+jsf+" From: <?php echo $this->uri->uri_string(); ?>");
initDatatable();
});
</script>

Have you tried $(el).ready(...)? That certainly ought to work. If it isn't, something else is going wrong.
Edit
Sorry, that should have been $("#your_xhr_loaded_content").ready()....
I do this type of thing all the time and it works, I think the key is that I am loading a document.
Main HTML document, index.html:
...
<body>
...
<div id="activity_content">
</div>
...
<script type="text/javascript" src="js/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
main.js:
...
function ruleManagement.loadContent() {
$.ajax({
url: "subdocs/ruleMgmt.html",
cache: false,
success: function(html) {
$("#activity_content").html(html);
}
}
}
ruleManagement.onReady = function(event) {
// Init contents of the rule_management_pane
...
}
HTML Sub-Document, ruleMgmt.html
<div id="rule_management_pane">
<!-- Content here -->
...
</div>
<script type="text/javascript" language="JavaScript">
jQuery("#rule_management_pane").ready(ruleManagement.onReady);
</script>
If I invoke ruleManagement.loadContent(), then ruleManagement.onReady() is called after div#rule_management_pane has been successfully loaded. I cannot say for sure that onReady is invoked before div#rule_management_pane is inserted into #activity_content, but I think that is the case.

how I understand your html/js is getting loaded:
containerPage --> $.get(/ajax/getMiddlePage.php)
middle XHR page --> $.get(/ajax/getContactQueue.php)
middle XHR page --> $.get(/ajax/getCurrentContactsTable.php)
rough. ok, here is what i think you need:
<html>
<!---CONTAINER PAGE--->
<head>
<script type="text/javascript">
//this .ready is to register events we need to catch the '#currentContactsTable' load event
$(document).ready(function(){
//ajaxSuccess is a global ajax function, you need to check ajaxOptions object to ensure you have the correct 'ajaxSuccess' you thought you did.
$.ajaxSuccess(function(event, XMLHttpRequest, ajaxOptions){
if (ajaxOptions.url == '/ajax/getCurrentContactsTable.php') {
$('#currentContactsTable').trigger('initDataTables');
}
});
// .live() does not need the element to exist on document.ready()
$('#currentContactsTable').live('initDataTables', function(event){
var dataTables = $(this).datatables({options:here});
});
});
</script>
</head>
<body></body>
</html>

This is what I came up with. Thx to respondents for help.
initPage();
function initPage(){
if(jq('#currentContactsTable').length==1){
initDatatable();
}else{
window.setTimeout(function(){
initPage();
},250);
}
}
function initDatatable(){
jq('#currentContactsTable').dataTable( {
//REST OF DATATABLE STUFF...
It may not be super pretty as it still is relying on a timeout, but at least this timeout it a bit more robust...
^^^^ BZZZZZZZZZ
The issue was something else, kinda. The script for Datatables is being loaded via getScript(). The element was being loaded normally, but initDatatables() was firing before getScript() was done loading, not before the el was loaded.
The solution was to call the initDatatables() function in the getScript() success callback:
<script type="text/javascript" charset="utf-8">
var jsf = '/js/jquery.dataTables.js';
jq.getScript(jsf, function(data, textStatus){
console.log('Loaded:'+jsf+" From: <?php echo $this->uri->uri_string(); ?>");
initDatatable();
});
</script>

Related

Reload the current page using Jquery and php after a function has been called

I am trying to reload the current page of this php through Jquery after the user has pressed the button. The function isset($_POST['submitGenZip']) gets called after the button is pressed but the Jquery is not able to run its function of reloading the page. The function isset($_POST['submitGenZip']) is only used to download a file (that is what the php does). It does not redirect to any page.
FirstPage.php
<?php
if(isset($_POST['submitGen']))
{
header('Location:Generate.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Zip Files</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
...
...
...
<tr>
<form action="" method="post" role="form">
<td>
<input type="submit" name="submitGen" class="btn btn-primary" value = "GenerateZ" style="float: right;">
</td>
</form>
</tr>
...
...
</body>
</html>
<script>
$(document).ready(function(){
$("#submitGen").click(function(){
alert("ReloadThisPage");
});
});
</script>
You can load your page or any other using multiple methods.
You do not have to use PHP to reload your current page or location. You can just do it jQuery OR JS instead.
Using location.reload()
You can use location.reload(); to reload your page on click event
Read more about location.reload here
Using window.open()
You can also use window.open('Generate.php') this will help if you want to open the URL in the new window.
Using window.location
You can also use window.location = 'Generate.php' this will help if you want to open the URL in the same window.
Run snippet below to see it working.
$(document).ready(function() {
$("#submitGen").click(function() {
alert('Page will reload now')
location.reload();
});
});
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Zip Files</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> ... ... ...
<tr>
<form action="" method="post" role="form">
<td>
<input type="submit" name="submitGen" id="submitGen" class="btn btn-primary" value="GenerateZ" style="float: right;">
</td>
</form>
</tr>
... ...
</body>
</html>
You can use HTML onclick Event Attribute
<input type="submit" onclick="location.reload()" name="submitGen" class="btn btn-primary" value = "GenerateZ" style="float: right;">
The user "AlwaysHelping" has helped me tackle the problem. However I would like to post an alternate solution. That is when the user downloads the file from the server, the request sent is sometimes slower than expected, the Jquery function runs during the same instance and the file is never downloaded. So I have kept a delay of 5 seconds in Jquery before refreshing the page.
<script>
$(document).ready(function() {
$("#submitGen").click(function() {
window.setTimeout(function () {
location.href = "FirstPage.php";
}, 5000);
});
});
</script>

iframe Element itself returns null?

My Google Chrome insists that my iframe is null. What's weird is that this returns the element without a hitch:
iframe = document.getElementById("main");
But then when I try to access any property of the iframe it says that I can't get a property from null (even through the element itself can be returned.)
I know I probably have to wait until it's loaded, but adding an event listener doesn't work because it gives me the same error.
EDIT: Some people asked for the context it is in...
<!DOCTYPE html>
<html>
<head>
<script src="index.js"></script>
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body onload="start()">
<noscript>Your browser is ancient and doesn't support JavaScript.</noscript>
<table>
<tr>
<th colspan=10 rowspan=1><h1>TITLE</h1></th>
</tr>
<tbody>
<tr rowspan=2><td colspan=10> </td></tr>
<tr rowspan=10>
<td colspan=10>
<div class="codegena_iframe">
<iframe src="about:blank" height="300" width="500" style="border:0px;float:middle;" id="main"></iframe>
</div>
</td>
</tr>
</tbody>
</table>
<font size="30"><div id="test"></div></font>
</body>
</html>
Here's my html element:
<iframe src="about:blank" height="300" width="500" style="border:0px;float:middle;" id="main"></iframe>
And here's my JavaScript:
iframe = document.getElementById("main");
function start() {
iframe.addEventListener("load", function() {
alert("foo");
});
}
Please help, I'm at a loss of what to do.
Thanks
It is more than likely that the DOM has not been completely loaded when your start function runs. You could remedy this problem in two ways.
Place your script after that iframe
Attach an event listener to the document that fires your code when the DOM is ready.
document.addEventListener('DOMContentLoaded', function (event) {
document.getElementById('main').addEventListener('load', function() {
console.log('The `iframe` has loaded!')
})
})
<iframe src="about:blank" height="300" width="500" style="border:0px;float:middle;" id="main"></iframe>

loading div before finishing all result data

I'm going sending data the Info page with ..$_get.. but I want when click ..a href=new.php?data=1.. to activate loading and Not all received data loading be enabled and after the completion information inside page new.php , loading deletion and .div id=result. is displayed or show information
new.php
<script type="text/javascript">
$(document).ready(function(){
$('a').click(function(){
$('#result').hide();
$('#main').html('<strong>loading...!</strong>;');
success:function(){
$('#main').html('');
$('#result').show();
}
});
});
</script>
<body>
<div id="main"></div>
test
<div id="result">
<?php
if(isset($_GET['data'])){
echo $_GET['data'];
}
?>
</div>
when click a href= Enable loading then when Information was received, remove loading and put the information in div result displayed
You made a mistake, click() isn't an ajax call so I don't understand why you put a success callback, try to remove it because it made a syntax JS error for sure.
There is the solution :
<script type="text/javascript">
$(document).ready(function(){
$('a').click(function(event){
$('#result').hide();
$('#main').html('<strong>loading...!</strong>;');
});
});
</script>
<body>
<div id="main"></div>
<div id="result">
<?php
if(isset($_GET['data'])){
echo $_GET['data'];
}
?>
</div>
</body>

jQuery .click on TD not firing

So I'm just trying to get a message box to pop up when I click a cell in my table. I have seen many threads about $("td").click(function () { etc, but these are not working for my table. I cannot find out why.
HTML:
<body>
<div id="tableArea">
<table class="table table-bordered" id="myTable">
<tr>
<td bgcolor="green" id='a1'>1</td><td>2</td>
</tr>
</table>
</div>
</body>
And the javascript/jQuery:
<script type="text/javascript">
$("td").click(function(e) {
alert('Anything');
});
</script>
I do not see a difference in this code than in many of the other threads, but this is not working. Note: I'm using Bootstrap, if that makes a difference.
You should capture the click event after $(document).ready().
<script type="text/javascript">
$(document).ready(function() {
$("td").click(function(e) {
alert('Anything');
});
});
</script>
$(document).ready( function(){
$("td").on('click', function(e) {
alert('Anything');
});
});
just work fine for your markup.
see it on jsfiddle

dynamically add table row in HTML Table in Javascript

I have following code:
<body onload="LoadData()">
<table id="myTable">
</table>
</body>
And I have Javascript function like :
<script type="text/javascript">
function LoadData()
{
var sTempTableRow='<tr><td>cell-1 </td><td>cell-2 </td><td>cell-3 </td><td>cell-4 </td></tr>'
$('#myTable').append(sTempTableRow);
}
</script>
I have tried numerous times and at all the times face an exception like Microsoft JScript runtime error: Object expected.
Please tell me what is the problem here.
Instead if the onload event use jquery's ready:
<script type="text/javascript">
$(document).ready(function()
{
var sTempTableRow='<tr><td>cell-1 </td><td>cell-2 </td><td>cell-3 </td><td>cell-4 </td></tr>';
$('#myTable').append(sTempTableRow);
});
</script>
<body>
<table id="myTable">
</table>
</body>
you can find the solution :
$(document).ready(function(){
var sTempTableRow='<tr><td>cell-1 </td><td>cell-2 </td><td>cell-3 </td><td>cell-4 </td></tr>'
$('#myTable').append(sTempTableRow);
});
​and remove the onload statement.
You can find the solution here.

Categories