I'm trying to post a form via Ajax, and I came across jQuery's POST, which sounds like the propper tool to use. I tried using the following html form:
<form id="my_form" action="http://localhost:4567/pedidos/guardar" method="POST">
Name:<br>
<input type="text" name="person_name"><br>
Amount:<br>
<input type="text" name="amount">
<br>
<input type="submit" value="Submit" id="submit_form">
</form>
<script type="text/javascript">
$('#submit_form').click( function() {
$.post( 'http://localhost:4567/pedidos/guardar', $('#my_form').serialize(), function(data) {
// ... do something with response from server
alert( "Data saved: " + data );
},
'json' // I expect a JSON response
);
});
</script>
This form was built based on this SO answer
I'm expecting to POST the form to /pedidos/guardar
. On the server side, to test that the form is properly posted, I created a really small Sinatra script:
require 'sinatra'
require 'json'
not_found do
status 404
"This page could not be found"
end
get '/' do
"Hello World!"
end
get '/pedidos' do
{ :person_name => "#{params[:person_name]}" }.to_json
end
post '/pedidos/guardar' do
#{}"I got #{params[:person_name]}."
{ :person_name => "#{params[:person_name]}" }.to_json
end
When using my form, I'm getting {"person_name":"Juan"}
, which is the expected response from Sinatra. But I'm not getting any alert window, it's like no Ajax is being used at all.
What am I missing in my form to make it work with Ajax? Do I need the action
and method="POST"
there?
Thanks in advance