The HTML Div Element vanishes as soon as the page is loaded

I encounter an issue when fetching HTML elements via AJAX and dynamically adding them to a DIV element. Sometimes, the DIV loads correctly, but other times it appears blank, even though the data is logged correctly in the browser. To provide more clarity, I have included links to screenshots of the problem.

Page loaded for the first time

Page refreshed multiple times and data is displayed

Data disappears after page refresh, despite correct AJAX retrieval

//////fetch table from database 
var getTable = function (id, value, tableId, context){

$.ajax({
url:'getJSON.php',
type:'POST',
dataType: 'json',
data:id+"="+value,
success:function(data){


console.log(data);

///////////////table/////////////

if(data.length>0)
{
  var table = $('#'+tableId).
  dataTable({
  "pageLength": 5,
  "lengthChange": false
  });
  var row,cell;
var count = Object.keys(data[0]).length;

for(i=0;i<data.length;i++){

   if(context.toLowerCase()==="classenroll")
   {
   table.fnAddData([
   data[i].CODE,
   data[i].NAME]);
}

if (context.toLowerCase()==="showmodifyassign") {

table.fnAddData([

    data[i].TITLE,

 data[i].DESCRIPTION,

 data[i].DEADLINE,

 data[i].NAME,

 "<a href=\"#\">Edit</a>"
]);

}


if (context.toLowerCase()==="submittedassignments") {

table.fnAddData([

data[i].STUDENT_ID,

data[i].FULL_NAME,

data[i].CLASS_NAME,

data[i].TITLE,

data[i].DEADLINE,

data[i].SUBMISSION_DATE,

"<a href = "+data[i].FILENAME+">"+"Download Now"+"</a>"
]);

}

if (context.toLowerCase()==="showdueassignments") {

table.fnAddData([

data[i].TNAME,

data[i].TITLE,

data[i].POSTINGDATE,

data[i].DEADLINE,

"<a target=\"_blank\" href = \"submit.php\">Submit</a>"
]);

}

if (context.toLowerCase()==="modifyclass") {


table.fnAddData([

data[i].CODE,

data[i].NAME,

data[i].DESCRIPTION,

"<a href = \"#\">Edit</a>"
]);

}
}
/////////////////////////////////////////////////
}
}
});



}


///code for the dynamic navbar

$("#wb_element_section_teacher").ready(function(e){
  
  getForm("homeTeacher");
  getTable($("#hTeacherTitle").val(),$("#hTeacherId").val(),"newAssignTable","submittedAssignments");
topMargin(0);


});

$('body').on('click', '#teacherHome', function(){
        
getForm("homeTeacher");            
getTable($("#hTeacherTitle").val(),$("#hTeacherId").val(),"newAssignTable","submittedAssignments");
tempHeight=650;
$("#wb_element_section_teacher").css('height',tempHeight+'px');
topMargin(tempHeight-divHeight);
return false;
});


$('body').on('click', '#createAssign', function(){

getForm("createAssign");
tempHeight=650;
$("#wb_element_section_teacher").css('height',tempHeight+'px');
topMargin(tempHeight-divHeight);
return false;
});


$('body').on('click', '#modifyAssign', function(){

getForm("modifyAssign");
tempHeight=950;
getTable("showMod","somevalue","modAssign","showmodifyassign");
$("#wb_element_section_teacher").css('height',tempHeight+'px');
topMargin(tempHeight-divHeight);
return false;
});


$('body').on('click', '#createClass', function(){

getForm("createClass");
tempHeight=650;
$("#wb_element_section_teacher").css('height',tempHeight+'px');
topMargin(tempHeight-divHeight);
return false;
});


$('body').on('click', '#modifyClass', function(){

getForm("modifyClass");
getTable("modClass","somevalue","modClass","modifyclass");
tempHeight=1000;
$("#wb_element_section_teacher").css('height',tempHeight+'px');
topMargin(tempHeight-divHeight);
return false;
});


$("#wb_element_section_teacher").ready(function(){

getForm("homeStudent");
getTable("due","somevalue","dueAssignments","showdueassignments");
topMargin(0);

});
} 

$('body').on('click', '#homeStudent', function(){

getForm("homeStudent");  
getTable("due","somevalue","dueAssignments","showdueassignments");          
tempHeight=650;
$("#wb_element_section_teacher").css('height',tempHeight+'px');
topMargin(tempHeight-divHeight);
return false;
});


$('body').on('click', '#enrollClasses', function(){

getForm("enrollClasses");
tempHeight=650;
$("#wb_element_section_teacher").css('height',tempHeight+'px');
topMargin(tempHeight-divHeight);
return false;
});


$('body').on('click', '#viewEnrolled', function(){

getForm("viewEnrolled");
getTable($("#hStudentTitle").val(),$("#hStudentId").val(),"enrolledClassesTable","classEnroll");
tempHeight=650;
$("#wb_element_section_teacher").css('height',tempHeight+'px');
topMargin(tempHeight-divHeight);
return false;
});


$('body').on('click', '#viewSent', function(){

getForm("viewSent");
getTable("sent","somevalue","sentAssignments","showsentassignments");
tempHeight=950;
$("#wb_element_section_teacher").css('height',tempHeight+'px');
topMargin(tempHeight-divHeight);
return false;
});

   

///////////

////JS to fetch the Elements (HTML)

getForm = function (userType){

$.ajax({

url: "forms.php",
type:"POST",
data:"type="+userType,
success:function(data){
console.log(data);
$("#wb_element_section_teacher").html(data);
return true;
}

});

}
<!--
In Javascript code:

hTeacherTitle.val() = "TEACHER_ID";
hTeacherId.val()=(Integer value) ID of the teacher returned from the Database;

-->



<!-- Code that is fetched when the page loads -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed " data-toggle="collapse" data-target="#navItems" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="glyphicon glyphicon-th-list"></span> </button>
</div>
<div id="navigation" class="col-md-12 ">

<ul class="nav nav-pills navbar-default collapse navbar-collapse nav-justified" id="navItems" >

<li id="teacherHome"><a href="#" class="navbar-text">Home</a></li>
<li id="createAssign"><a href="#" class="navbar-text">Create Assignment</a></li>
<li id="modifyAssign"><a href="#" class="navbar-text">Modify Assignments</a></li>
<li id="createClass"><a href="#" class="navbar-text">Create Class</a></li>
<li id="modifyClass"><a href="#" class="navbar-text">Modify Class</a></li>


</ul>

</div>

<div class="container-fluid" style="margin-top:10%;"> <center><h3>New Assignments</h3></center>
</div>
<div id="newAssign">
<table id="newAssignTable" class="table table-bordered table-striped">
 
<thead>
<tr>
<th>Student's ID</th>
<th>Student's Name</th>
<th>Class Name</th>
<th>Assignment Title</th>
<th>Due Date</th>
<th>Submission Date</th>
<th>Download</th>
</tr> 
</thead>
   
<tbody>
</tbody>
 
</table>

</div>

Answer №1

Attempting to load this HTML via Ajax during DOM readiness? Consider utilizing $(document).ready() instead of

$("#wb_element_section_teacher").ready()
.

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

Exploring the Unpredictable Results of Recursive Functions in JavaScript

Take a look at this recursive code snippet. function calculateFactorial(n) { if (n === 0 || n === 1) { return 1; } else { console.log(calculateFactorial( (n - 1) )); return n * calculateFactorial(n - 1); } } const num = ...

Is it possible to display a Twitter feed within a Bootstrap popover?

Is it feasible to showcase a Twitter feed within a Bootstrap popover? For instance, when the Twitter button is clicked, I aim to have my website's Twitter feed appear inside a Bootstrap popover. I have attempted the code below without success. Any a ...

What is the mechanism behind `minmax` generating multiple columns in CSS Grid when it is given a value of `1fr`?

Consider the code snippet provided. According to my understanding, the columns in this grid are set to be a minimum of 150 pixels wide and maximum of "1 fraction" of the container width. My question is, how does the grid determine when to add more columns ...

Bootstrap causing issues with correct display of div element

I'm having trouble getting my divs to display on the same row. It seems like when I have 2 rows, the button is positioned correctly. However, with only one row, the button ends up on the second row. Here is the current layout: https://i.sstatic.net/L ...

Designing Angular2 application structure for various platforms (web, mobile, native)

Imagine an ng2 application that caters to multiple platforms such as web, mobile-web, and mobile-native. Due to the presence of shared files like action creators, reducers, services, and common components across these platforms, it's feasible to have ...

At what point are functions executed? What methods can I use to manage their execution?

Looking to make a simple call to an API using jQuery's $.get() function as a JS beginner. The issue I'm facing is that the function seems to be called randomly rather than where I expect it in my code. I am open to either doing everything inside ...

How to Extract a URL from an Anchor Tag without an HREF Attribute Using Selenium

How can I make a link, which normally opens in a new window when clicked, open in the current window instead? The link does not have an href attribute, only an id and a class. For example: <a id="thisLink" class="linkOut">someLinkText</a> I r ...

Why doesn't my constructor promise to not replace data?

I need help figuring out where I'm going wrong with my code. I have a class that has a constructor and two methods. My goal is for the `find()` method to push data from a query into an array. However, I'm not sure why the array values seem to dis ...

There are certain lines of JavaScript/Node.js code that are failing to execute

app.get is not being executed. I have also attempted to include app.listen(3000). My goal is to retrieve the parameter passed from the first web page. This code is designed to fetch parameters sent by another web page and then construct a MySQL query and ...

Is there an issue with my Ajax request?

I've been troubleshooting an issue where my function consistently returns an error condition when trying to make a simple Ajax call to a local JSON file. I've ruled out the possibility that it's a file system call by uploading the file, but ...

Experiencing issues with HTTPS and AJAX in Laravel specifically on Safari and a handful of other browsers

I am encountering an error when making a post request using AJAX. The error message is as follows: PHP Parse error: syntax error, unexpected '/*' (T_STRING), expecting ')' in /home/laravel/public_html/public/index.php on line 47 PHP ...

What is the best way to add a line break in a Babylon JS dynamic texture when using the drawText function?

Recently, I came across a demo that caught my interest. You can check it out here: If you're curious about the source code, you can find it here: https://github.com/jeromeetienne/threex.dynamictexture/blob/master/examples/basic.html This demo showca ...

I am having trouble getting pagify.js to function properly

Looking to incorporate the pagify.js plugin into my website by following the steps on Github. After downloading the repo, I tried opening the index page in Chrome for a preview, but encountered errors (see image). https://i.sstatic.net/WHOWS.png Need h ...

How can I extract the filename from a form using PHP and HTML?

I have the following code snippet: <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> ...

Is there a way in Vue.js for me to access a method from within the same component using the component's data?

Below is the code for a specific component: <template> <li v-for="(item, i) in this.menu" :key="i" @click="item.action()"> //attempting to call the method in the component {{menu.title}} <li> </template> <script> ...

Include two arguments when making a $http POST request

I am facing a situation where a single property can have multiple images, but each image can only be assigned to that one property (one-to-many relationship with propertyId as foreign key). In the HTML, I am fetching the propertyId and passing it along wi ...

retrieve the documents that correspond to a specific string in mongoose

Currently, I am working on integrating a search feature into a MERN stack application. The idea is to utilize the searchWord extracted from req.params.searchWord and fetch results containing that specific searchWord. Although my existing code serves its p ...

Leverage the power of the YouTube API to determine if a video is able to be embedded

As I delve into the YouTube Data API v3 to determine if a particular video is embeddable, I have come across the status.embeddable property that seems crucial. By making a request like this: https://www.googleapis.com/youtube/v3/videos?id=63flkf3S1bE& ...

Exploring the Prototype-based programming concept in JavaScript

I am determined to deepen my understanding of JavaScript and explore what lies beneath its surface. While I have delved into various guides on the Object-Oriented Paradigm with Prototypes in JavaScript, I am struggling to comprehend how this paradigm diffe ...

Differences Between JavaScript KeyCode and CharCodeIn the world

Issue at Hand: The challenge is to restrict allowed characters in an HTML input field to only a-z and A-Z. It is essential for business requirements that this restriction happens on KeyPress, preventing disallowed characters from even appearing in the in ...