Brad
Brad

Reputation: 1691

Very Simple Ajax Question

I am just learning JQuery and have a few scripts successfully working on my site. Until I get to what the JQuery for nitwits book calls Ajax. I am trying to do this very simple script

<div class="menu">
<script>
$(function(){
$('div').load('mytext.txt');
});
</script>

<div id="here"> </div>
</div>

I have tried this on pages where JQuery works just fine so I know my link to google works. I have tried a couple small scripts like this one and cannot get them to work under any circumstances. Mytext.txt is in the same directory as the php file with the script. Is there some magic word you have to use in order to make .load work?

I have tried

$('div#here').load('mytext.txt');

to no avail. Of special note this is on a codeigniter site, but that shouldn't matter being as I am calling ajax independent of the controller and straight from the views like any other JQuery call.

This should be the simplest thing in the world. Why can I not do anything to get .load to work? Thanks

Upvotes: 1

Views: 121

Answers (3)

T.P.
T.P.

Reputation: 2995

This following snippet is working correctly on my Linux hosting environment. Both of the files (so.html and mytext.txt are located in the document root.) I wonder if not specifying the "type" attribute with the script tag is causing you some issues. You also want to make sure to qualify the div selector as well: $('div#here').load... as opposed to $('div').load...

File = /so.html

<!DOCTYPE html>
<html>
<head>
<title>Stackoverflow is Awesome</title>
<script
  type="text/javascript"
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
</head>
<body>
<div class="menu">
  <div id="here"></div>
</div>
<script type="text/javascript">
  $(function(){
    $('div#here').load('mytext.txt');
  });
</script>
</body>
</html>

File = /mytext.txt

Hello from mytext.txt!!!!!

Upvotes: 1

icyrock.com
icyrock.com

Reputation: 28608

This should be working along the lines you gave - see a working jsfiddle here:

The only thing I can think of is to check the path to the file (maybe it should be /mytext.txt, i.e. with a slash in front). Also, can you open the file from within your browser, i.e. browse to www.yoursite.com/mytext.txt?

As a side note, <script> tags should generally go to <head> element in your HTML.

Upvotes: 1

David Laing
David Laing

Reputation: 7665

Try running your page using Firefox with Firebug enabled; and watch the NET/HTTP traffic.

My guess is that there is a relative path issue; but Firebug should give you some more detail as to what the exact error is when mytext.txt is requested.

Upvotes: 2

Related Questions