[jQuery] don't follow a link, just inject datat into the DOM

Hi,

I have a link which shouldn’t lead to another page. When clicking on it, a remote page is silently loaded into the dom. Everything works fine. I just wish I could avoid the # to be added to the querystring.

Here’s what I get:


<script src="jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){
  $("a#test").click(function(){
    $("div#content").load("http://localhost/jquery_tests/content.php")
  });
});


</script>


<a href="#" id="test">test</a><!-- remove the # --!>
<div id="content"></div>

Regards,

-jj. :slight_smile:

To stop a link from activating, use return false.

$(document).ready(function(){
  $("a#test").click(function(){
    $("div#content").load("http://localhost/jquery_tests/content.php");
    return false;
  });
});

Thanks for your reply. :slight_smile:

One more question:

Is there a way to dynmically pass data to “content.php”? Like mimicking a querystring?


<a href="#" class="test" id="1">test1</a>
<a href="#" class="test" id="2">test2</a>
<a href="#" class="test" id="3">test3</a>
<a href="#" class="test" id="4">test4</a>


$(document).ready(function(){
  $("a#test").click(function(){
    $("div#content").load("http://localhost/jquery_tests/content.php?id=id"); //id captured in the link
    return false;
  });
});

Which would end up loading the content.php page and passing to it id=1, id=2, id=3 and id=4 depending on which link gets clicked.

Regards,

-jj.:slight_smile:

Sure.

$(document).ready(function(){
  $("#test").click(function(){
    $("#content").get("http://localhost/jquery_tests/content.php", {param: value, param2: value2});
    return false;
  });
});

Change “.get(” to “.post(” if needed.

Thanks :slight_smile:

Where do I set this? In my html anchor?


{param: value, param2: value2}

Is there a better to way to do achieve what I’m trying to achieve here or is the regular approach?

:slight_smile:

You would just set it as written above.

ID’s should not start with a number.

Try this:


<a href="#" class="test" id="a1">test1</a>
<a href="#" class="test" id="a2">test2</a>
<a href="#" class="test" id="a3">test3</a>
<a href="#" class="test" id="a4">test4</a>


$(document).ready(function(){
  $("a#test").click(function(){
    $("div#content").load("http://localhost/jquery_tests/content.php?id=" + $(this).attr('id').substr(1)); //id captured in the link
    return false;
  });
});

Thanks for your reply :slight_smile:

Why?

:slight_smile:

I was wondering if there would be a way to do the same as the above with links designed this way:


<a href="http://localhost/blah/id/24/" class="test">test4</a>