I basically want to create an alert when clicking on a button, withour reloading the entire page.
Into my view :
:javascript
function ajax_test1(field)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "test_ajax.xml?code=" + field.value, false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
alert(xmlDoc.getElementsByTagName("message")[0].childNodes[0]);
}
and
= button_to 'test ajax', :remote => true, :onclick => "ajax_test1(this);"
Into my controller
def test_ajax
@test = {message:'Hello there!'}
render :xml => @test
end
When I click on the button, the page is reloading with the following URL:
http://localhost:4242/test?onclick=ajax_test1%28this%29%3B&remote=true
How can I fix this please?
I changed this :
into this:
and it worked!
The onclick event needs to return
false
in order to halt the default behaviour – the actual click – from taking place.If you were using jQuery, the
.preventDefault()
method is a nicer way of preventing the default event behaviour – but with your hand rolled javascript you'll have to be a bit messier: