Loading div content within the div

C++, C#, Java, PHP, ect...
Post Reply
User avatar
Torniquet
Posts: 869
Joined: Sun Aug 02, 2009 6:18 am

Re: Loading div content within the div

Post by Torniquet »

I dont know how to do it in plain JS.

But the jQuery equiv (look up jquery and download the library... makes ajax/javascript functionality MUCH easier)

Code: Select all

<a href="somepage.php" onclick="$('#idOfDivToLoadInto').load($(this).attr("href")); return false;">page</a>

<div id="idOfDivtoLoadInto">
    <!-- Empty div ready to be populated -->
</div>

Shouldn't be to hard to work out :)
New Site Coming Soon! Stay tuned :D
User avatar
Chris
Posts: 1580
Joined: Wed Sep 30, 2009 7:22 pm

Re: Loading div content within the div

Post by Chris »

Torn's method is a quite an easy way of doing it, but it uses DHTML, while this works, I tend to avoid it as editing the HTML each time tends to be a pain in the neck. I prefer making JavaScript events using JavaScript itself:

Raw JavaScript (important to know the workings):

http://www.w3schools.com/dom/dom_http.asp

Code: Select all

<!DOCTYPE html>
<html>
	<head>
		<title>Hello!</title>
	</head>
	<body>
		<a href="#">Click here and watch the magic happen</a>
		<div id="myDiv" style="border: #000 1px solid;">this div will contain the response :D</div>

		<script type="text/javascript">
		document.getElementsByTagName('a')[0].onmousedown = function() // the first link on the page has been clicked
		{
			var ajax = new XMLHttpRequest(); // create a new XMLHttpRequest object

			ajax.open('GET', 'myFile.html');
			ajax.send(0); // to this day I still don't know why you need to pass a parameter

			ajax.onreadystatechange = function() // goes through 5 changes, 0,1,2,3,4
			{
				if( ajax.readyState != 4 ) // waiting
				{
					document.getElementById('myDiv').innerHTML = 'Loading...'; // fill in our div with 'Loading...'
				}
				if( ajax.readyState == 4 ) // good to go, request is complete, we should have our content
				{
					document.getElementById('myDiv').innerHTML = ajax.responseText; // fill our div with the response
				}
			}
		}
		</script>

	</body>
</html>
using jQuery (download from http://jquery.com/):

http://api.jquery.com/jQuery.get/

Code: Select all

<!DOCTYPE html>
<html>
	<head>
		<title>Hello!</title>
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"> // inculde jquery </script>
		<script type="text/javascript">
		$(document).ready( function()
		{
			// add a click event to our link
			$('a[href="#"]').click( function()
			{
				$.get('myFile.html', function(data)
				{
					$('#myDiv').html(data); // fill our div with the data
				});
			})
		});
		</script>
	</head>
	<body>
		<a href="#">Click here and watch the magic happen</a>
		<div id="myDiv" style="border: #000 1px solid;">this div will contain the response :D</div>
	</body>
</html>
Fighting for peace is declaring war on war. If you want peace be peaceful.
User avatar
Torniquet
Posts: 869
Joined: Sun Aug 02, 2009 6:18 am

Re: Loading div content within the div

Post by Torniquet »

Im not sure what your problem is.

It seems to be working fine for me.
New Site Coming Soon! Stay tuned :D
User avatar
Chris
Posts: 1580
Joined: Wed Sep 30, 2009 7:22 pm

Re: Loading div content within the div

Post by Chris »

Still can't follow this completely. When you say "it won't," What is is doing?
Fighting for peace is declaring war on war. If you want peace be peaceful.
User avatar
Chris
Posts: 1580
Joined: Wed Sep 30, 2009 7:22 pm

Re: Loading div content within the div

Post by Chris »

Code: Select all

<!DOCTYPE html>
<html>
	<head>
		<title>Like this?</title>
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
		<script type="text/javascript">

		$(document).ready( function()
		{
			// needs to be regenerated every time the page changes
			function generate()
			{
				$('a').click( function(e)
				{
					e.preventDefault();

					$.get( $(this).attr('href'), function(data)
					{
						fillFrame(data)
					})
				});

				$('form').submit( function(e)
				{
					e.preventDefault();

					var method = $(this).attr('method'),
						action = $(this).attr('action'),
						values = {};

					$.each($(this).serializeArray(), function(i, field)
					{
					    values[field.name] = field.value;
					});

					$.ajax({
						type : method,
						url : action,
						data : values,
						success : function(data)
						{
							fillFrame(data)
						}
					})
				})

			}

			// saves time like this :D
			generate();

			// function that fills the frame and updates again
			function fillFrame(data)
			{
				$('#frame').html(data)
				generate(); // <- regenerate
			}
		});
		</script>
	</head>

	<body>
		<a href="lol.html">lol?</a>
		<a href="haha.html">oh.. haha</a>
		<div id="frame">
		</div>
	</body>
</html>
lol.html

Code: Select all

lol
haha.html

Code: Select all

<form method="post" action="test.php">
	<input type="text" value="input1" name="name" /><br />
	<input type="text" value="test@lol.lol" name="email" /><br />
	<input type="text" value="hah" name="whatever" />
	<input type="submit" value="GO »" />
</form>
test.php

Code: Select all

<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
    foreach( $_POST as $index => $value )
    {
        echo $index . ' = ' . $value . '<br />' . "\n";
    }
}
else
{
    foreach( $_GET as $index => $value )
    {
        echo $index . ' = ' . $value . '<br />' . "\n";
    }
}
?>
<a href="haha.html">haha</a>
Fighting for peace is declaring war on war. If you want peace be peaceful.
User avatar
MikeD
Posts: 294
Joined: Thu Sep 08, 2011 4:28 am

Re: Loading div content within the div

Post by MikeD »

Chris wrote:
using jQuery (download from http://jquery.com/):

http://api.jquery.com/jQuery.get/

Code: Select all

<!DOCTYPE html>
<html>
	<head>
		<title>Hello!</title>
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"> // inculde jquery </script>
		<script type="text/javascript">
		$(document).ready( function()
		{
			// add a click event to our link
			$('a[href="#"]').click( function()
			{
				$.get('myFile.html', function(data)
				{
					$('#myDiv').html(data); // fill our div with the data
				});
			})
		});
		</script>
	</head>
	<body>
		<a href="#">Click here and watch the magic happen</a>
		<div id="myDiv" style="border: #000 1px solid;">this div will contain the response :D</div>
	</body>
</html>
Is the only way to do this by using the '#' symbol? I can't get it to work with anything else other than that, even when I do change the $('a[href="#"]').click( function() to whatever symbol.
User avatar
Chris
Posts: 1580
Joined: Wed Sep 30, 2009 7:22 pm

Re: Loading div content within the div

Post by Chris »

MikeD wrote:
Chris wrote:
using jQuery (download from http://jquery.com/):

http://api.jquery.com/jQuery.get/

Code: Select all

<!DOCTYPE html>
<html>
	<head>
		<title>Hello!</title>
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"> // inculde jquery </script>
		<script type="text/javascript">
		$(document).ready( function()
		{
			// add a click event to our link
			$('a[href="#"]').click( function()
			{
				$.get('myFile.html', function(data)
				{
					$('#myDiv').html(data); // fill our div with the data
				});
			})
		});
		</script>
	</head>
	<body>
		<a href="#">Click here and watch the magic happen</a>
		<div id="myDiv" style="border: #000 1px solid;">this div will contain the response :D</div>
	</body>
</html>
Is the only way to do this by using the '#' symbol? I can't get it to work with anything else other than that, even when I do change the $('a[href="#"]').click( function() to whatever symbol.
No, that was more for the example, I like to add these things so people ask questions. So well done to you.

Basically jQuery makes use of CSS like selectors. http://www.w3.org/TR/selectors/#selectors

You might notice in the HTML I have an anchor with the href attribute set to #.

Code: Select all

<a href="#">Click here and watch the magic happen</a>
Basically $('a[href="#"]') will search for all a tags with the attribute href set to #, I could search for anything I want though.

Code: Select all

$('a[href="lol.php"]').click( function() { alert('haha') } );

Code: Select all

<a href="lol.php">lol</a>

Code: Select all

$('a[id="myLink"]').click( function() { alert('haha') } );

Code: Select all

<a href="lol.php" id="myLink">lol</a>
or simply:

Code: Select all

$('#myLink').click( function() { alert('haha') } );
You can also just simply search all anchor elements:

Code: Select all

$('a').click( function(){ alert($(this).attr('href')) });

Code: Select all

<a href="haha">lol</a><br />
<a href="pff">:D</a>

This can of course also be used for different types of elements:

Code: Select all

$('input').click( function() { alert('you clicked the button') } );

Code: Select all

<input type="button" value="click me" />
Fighting for peace is declaring war on war. If you want peace be peaceful.
User avatar
MikeD
Posts: 294
Joined: Thu Sep 08, 2011 4:28 am

Re: Loading div content within the div

Post by MikeD »

Sadly my knowledge of Ajax/JQ/JS is minimal at best, and I was unable to get any of that to work.

However, I did finally get your script to work the way I wanted it to.

The Market in my game has 4 different sections to it. One for weapons, armor etc. So, when a certain link was clicked (To whatever part of the market) I needed it to load that part of the market. I couldn't get it to work with anything other than the #

So, here's what I did, it may look like ugly coding, but it does get the job done, unless there's a more efficient way to do it.

Code: Select all

<!DOCTYPE html>
<html>
   <head>
      <title>Hello!</title>
      <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"> // inculde jquery </script>
      <script type="text/javascript">
      $(document).ready( function()
      {
         // add a click event to our link
         $('a[href="#1"]').click( function()
         {
            $.get('myFile.html', function(data)
            {
               $('#myDiv').html(data); // fill our div with the data
            });
         })
      });
      </script>
      
            <script type="text/javascript">
      $(document).ready( function()
      {
         // add a click event to our link
         $('a[href="#2"]').click( function()
         {
            $.get('myFile2.html', function(data)
            {
               $('#myDiv').html(data); // fill our div with the data
            });
         })
      });
      </script>
   </head>
   <body>
      <a href="#1">Click here and watch the magic happen</a>
      <a href="#2">Click here and watch the magic happen</a>
      <div id="myDiv" style="border: #000 1px solid;">this div will contain the response :D</div>
   </body>
</html>
User avatar
Chris
Posts: 1580
Joined: Wed Sep 30, 2009 7:22 pm

Re: Loading div content within the div

Post by Chris »

This is a more efficient way:

Code: Select all

<!DOCTYPE html>
<html>
   <head>
      <title>Hello!</title>
      <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"> // inculde jquery </script>
      <script type="text/javascript">
      $(document).ready( function()
      {
         // add a click event to our link
         $('a').click( function(e)
         {
            e.preventDefault();
            var href = $(this).attr('href')

            $.get(href, function(data)
            {
               $('#myDiv').html(data); // fill our div with the data
            });
         })
      });
      </script>
   </head>
   <body>
      <a href="myFile.html">Click here and watch the magic happen</a>
      <a href="myFiel2.html">Click here and watch the magic happen</a>
      <div id="myDiv" style="border: #000 1px solid;">this div will contain the response :D</div>
   </body>
</html>
Fighting for peace is declaring war on war. If you want peace be peaceful.
User avatar
MikeD
Posts: 294
Joined: Thu Sep 08, 2011 4:28 am

Re: Loading div content within the div

Post by MikeD »

Chris wrote:This is a more efficient way:

Code: Select all

<!DOCTYPE html>
<html>
   <head>
      <title>Hello!</title>
      <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"> // inculde jquery </script>
      <script type="text/javascript">
      $(document).ready( function()
      {
         // add a click event to our link
         $('a').click( function(e)
         {
            e.preventDefault();
            var href = $(this).attr('href')

            $.get(href, function(data)
            {
               $('#myDiv').html(data); // fill our div with the data
            });
         })
      });
      </script>
   </head>
   <body>
      <a href="myFile.html">Click here and watch the magic happen</a>
      <a href="myFiel2.html">Click here and watch the magic happen</a>
      <div id="myDiv" style="border: #000 1px solid;">this div will contain the response :D</div>
   </body>
</html>
PERFECT! Thank you!

I really need to find the time to learn JS. I've seen alot of cool things done with it.
Post Reply

Return to “Coding”