CodeyMonkey
CodeyMonkey

Reputation: 739

jQuery/AJAX - Load content into a div when button clicked?

Would someone be able to help here?

I would like to fill a div e.g.

<div id="contenthere"></div>

with content from an external file e.g.

/includes/about-info.html

when a button with a certain class is clicked e.g.

<p class="classloader">Click Here</p>

Does anyone have a quick code example they can show me to achieve this?

Upvotes: 8

Views: 49067

Answers (5)

m1k1o
m1k1o

Reputation: 2364

Load latest version of jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

jQuery code:

<script language="javascript">
$(function(){
  $(".classloader").click(function(){
    $("#contenthere").load("/includes/about-info.html");
  });
});
</script>

HTML code:

<p class="classloader">Click Here</p>
<div id="contenthere"></div>

Upvotes: 4

Saurabh Sharma
Saurabh Sharma

Reputation: 37

Use this simple and sobher it also do run time binding as well:

$(document).ready(function(){
    $(document).on('click','.classloader',(function(){
        $('#contenthere').load('/includes/about-info.html');
    });
})

Upvotes: 0

Nirav Gandhi
Nirav Gandhi

Reputation: 2005

Try the following:

var myurl = 'myfileonthesamedomain.html';

$('button').click(function(){
    $('div.loadme').load(myurl);
});

Upvotes: 0

Mariusz Jamro
Mariusz Jamro

Reputation: 31653

Use jQuery.click and jQuery.load:

$(document).ready(function(){
    $('.classloader.').click(function(){
        $('#contenthere').load('/includes/about-info.html');
    });
})

Upvotes: 14

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

You could subscribe to the .click() event of the paragraph and then use the .load() function to send an AJAX request to the given url and inject the results into the specified selector:

$(function() {
    $('.classloader').click(function() {
        $('#contenthere').load('/includes/about-info.html');
        return false;
    });
});

Upvotes: 1

Related Questions