So assuming that you have something that looks like
<a href="#" onClick="someClickHandler(); return false;">Click Here</a>
<div id="foo">Hello World!</div>
I recommend using jQuery:
<script type="text/javascript">
function someClickHandler() {
var text = $("#foo").text();
$.get("url_on_the_server", {some_query_parameter_name: text}, function(response){
// do something with the response you get back from the server
});
}
</script>
Here's what this is doing:
The onClick
attribute causes the someClickHandler
function to be called when the link is clicked. Because we put return false
in that attribute, the browser will not try to follow the link; instead when clicked it will just execute the click handler and stop.
Saying $("#foo")
finds the element on the page with an id
of "foo", as documented here. Saying $("#foo").text()
returns everything inside that div as text, as documented here.
The $.get
call is explained at depth in the jQuery documentation here. Basically you're making an AJAX request to the server and passing the text from the div as a query parameter. The function you pass to $.get
defines what you do with the response you get back from the server.
Of course, you could also use the jQuery click method instead of manually setting the onClick
attribute yourself, but I figured that this way would be somewhat more intuitive for a beginner.