views:

42

answers:

3

I have an ajax function that is not run when the ajax script is included in my HTML page like so:

<script type='text/javascript' src='ajax.js'></script>

However, if I place the exact same script in the head portion of the HTML page, then it does run.

Why does this occur, and how can I fix it?

<script type="text/javascript"> 
        $(function() {

            $(".a").click(function() 
            {    
                  $.ajax({
                     type: "POST",
                     url: "1.php",
                     data: dataString,
                     cache: false,
                     success: function(html)
                       {
                           //stuff
                       }  
                   });

                return false;
            });

        });

</script> 
A: 

can you post the actual ajax script you are talking about?

Zumo
done! hope it helps
Sev
A: 

I made a example which worked fine for me. cant see any problems so im guessing its a mistype or something silly.

here is the sample code i used:

HTML: //double check these paths

<body>
<a class="a" href="#">clicky</a>
</body>

Javascript:

$(function() {
// i noticed you put .a here instead of a, i am assuming you are referring the class
$(".a").click(function() 
{    
    alert("1");
      $.ajax({
         type: "POST",
         url: "1.php",
         data: "html",
         cache: false,
         success: function(data)
           {
         //stuff
         $("body").html(data);
           }  
       });

    return false;
});

});

PHP:

echo 'bar';
Zumo
and you included the javascript using something like this: <script type='text/javascript' src='ajax.js'></script> ?
Sev
yep this is the exact html i put in my file:<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><script type='text/javascript' src='ajax.js'></script>
Zumo
weird indeed. i will test it again. thanks.
Sev
+1  A: 

This might seem trivial but did you remove the <script> tags when using it in an external .js file?

The contents of your ajax.js file should just be:

$(function() {
  $(".a").click(function() {    
    $.ajax({
      type: "POST",
      url: "1.php",
      data: dataString,
      cache: false,
      success: function(html)
      {
        //stuff
      }  
    });
    return false;
  });
});

I have the impression that when you mentioned "exactly", you left the script tags intact in the ajax.js file.

Also if this still doesn't work. try added an alert("hello"); line at the top of ajax.js before everything to see whether it runs at all.

sirhc
hehe, dumb mistake on my part, but you caught it! good job :)
Sev
No problem. Happy scripting! :)
sirhc