Kamyar Parastesh Kamyar Parastesh - 4 months ago 15
Ajax Question

call parital html page using jQuery

I want to call a partial html page using jquery. I have seen this

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="lib/jquery-3.1.0.min.js"></script>
<script type="text/javascript"> $('#result').load('Ajax/test.html'); </script>
<title>Home</title>
</head>
<body>
<div id="result"></div>

</body>


</html>


and in the path
Ajax/test.html
i have this test.html:

<h1>Hey World</h1>


The problem is it does not load the
Hey World
into the main page. Also, there is no error in console.
What is the problem?

Answer

As with $('#result'), jQuery is unable to find the element as DOM is not ready hence jQueryObject.load method is never invoked.

Wrap your script in $(document).ready or Place your <script> as last-child of <body>(Just before closing body tag(</body>))

There are also DOMContentLoad or window.onload events which makes sure that DOM is loaded but IMO, placing <script> just before </body> is easier option.

<div id="result"></div>
<script>
  $('#result').load('test.html');
</script>