Randy Tang
Randy Tang

Reputation: 4353

Ajax: div wouldn't get updated

Can somebody tell me what's wrong with the following code? It always updates to a new page, instead of the "content" div. Thanks.

This is a test:<br />
   <a href="/form" onclick="return updateContent()">Click me</a>
     <div id="content">
       Update here.
   </div>

<script>
function updateContent() {
  $.ajax({
    type: 'GET',
    url: $(this).attr('href'),
    success: function(data) {
      $('#content').html(data);
    };
 });
};
</script>

Upvotes: 0

Views: 176

Answers (3)

user1823761
user1823761

Reputation:

Liang Tang. You have syntax error in your javascript code here:

success: function(data) {
  $('#content').html(data);
};

there is no need ; after }. Anyways, this is the correct answer. Also don't use internal events like onclick in your HTML markup. Let's javascript/jquery handle them for you.

This is a test:<br />
<a href="form.html" id="link">Click me</a>
<div id="content">
Update here.
</div>

<script>
$(function () {
    $('#link').bind('click', function (e) {
        e.preventDefault();

        $.ajax({
            type: 'GET',
            url: $(this).attr('href'),
            success: function(data) {
              $('#content').html(data);
            }
         });
    });
});
</script>

Explanation
1. I give your link an specific ID. So I can access it in jquery code.
2. In the click event of link, I cancel the link behaviour (with e.preventDefault())

Upvotes: 1

j08691
j08691

Reputation: 207881

Since you're using jQuery, you might as well use it properly. Your link is doing what links are meant to do since you have nothing that cancels the default behavior of the link.

Change:

<a href="/form" onclick="return updateContent()">Click me</a>

to

<a href="/form">Click me</a>

And change your jQuery to:

$('a').click(function(e) {
    e.preventDefault();
    $.ajax({
        type: 'GET',
        url: $(this).attr('href'),
        success: function(data) {
            $('#content').html(data);
        };
    });
});​

Upvotes: 1

VenkatK
VenkatK

Reputation: 1305

Instead writing <a href="/form" onclick="return updateContent()">Click me</a>, write the following.
<span style="cursor:pointer;" onclick="return updateContent()">Click me</span>
The above will work.

Upvotes: 0

Related Questions