views:

70

answers:

2

Trying to load an external php file into another onClick. Iframes will not work as the size of the content changes with collapsible panels. That leaves AJAX. I was given a piece of code

HTML

<a href="#" id="getData">Get data</a>
<div id="myContainer"></div>
JS

$('#getData').click(function(){
    $.get('data.php', { section: 'mySection' }, function(data){
       $('#myContainer').html(data);
    });
});
PHP:

<?php
    if($_GET['section'] === 'mySection') echo '<span style="font-weigth:bold;">Hello World</span>';
?>

I have tested it here http://www.divethegap.com/scuba-diving-programmes-dive-the-gap/programme-pages/dahab-divemaster/divemaster-trainingA.php and get the most unexpected results. It certainly loads the right amount of items as it says in the lower bar on safari but I see three small calendars and that is it. Can anyone see where I have made a mistake?

+1  A: 

First things first, you want to have the jQuery bit inside the ready function $(document).ready(function(){..}. In your test page, there is already a ready function at the top which contains the line $('a[rel*=facebox]').facebox(), so you might want to put the code there.

Secondly, you want to prevent the link from going to the default action, which is to load the url '#'. You do that with the preventDefault() method.

I tested and confirmed that the following code should work for you:

<script type="text/javascript">
  $(document).ready(function(){
    $('#getData').click(function(event){
      event.preventDefault();
      $.get('test.php', { cat: 16 }, function(data){
        $('#myContainer p').html(data);
      });
    });
});</script>

You can find more details and examples of jQuery's get function here.

ewall