This has been asked a few times, however, there seems to be no good answer on the web. To avoid replies or links which do not answer this question, I will rephrase it. A page has only a form with input text (and button). We post text to the server and want it just sent back and alerted. In other words, the view should have the line:
$.post(...,$("form").serialize(),function(reply){alert(reply);});
With PhP, the answer is an "echo" one-liner. Can this be done in Sinatra - I understand that backend frameworks are built around handling DOM manipulation themselves. I am asking this question because it would be nice to use a more expressive language such as Ruby also just for db interface/backend logic.
Edit: This is the /views/index.erb
(with "/reply" in place of "reply.php" - otherwise index.html/index.php) part:
<script src="jquery"></script>
<form action="reply.php" method="post"><input type="text" name="t"></form>
<script>
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
$.post("reply.php",$("form").serialize(),function(reply){alert(reply);});
});
});
</script>
Note that with event.preventDefault()
we stay at /
route and don't go into /reply.php
,
which would remove the form and print just the submitted text. In other words, this is
what enables Ajax and we get a reply (only in alert) from the server with reply.php
:
echo $_POST["t"];
With Sinatra, we need to have a routes.rb
controller:
require 'sinatra'
get '/' do
erb :index
end
post '/reply' do
...
end
Question: With index.html/reply.php
we get an alert with posted text. How can index.erb
/routes.rb
be modified also to get an alert with posted text?