Reputation: 4060
I am trying to pass a javascript variable from my view to my controller via ajax according to the example shown here: Passing JavaScript variable to ruby-on-rails controller
my controller "pages_controller.rb" contains the following method:
def test_page
@message= params[:id]
puts @message
end
the respective view "test_page.html.erb" contains javascript with an ajax call which is triggered by clicking a button:
<button id="submit_button">Submit Text</button>
<script>
$("#submit_button").on('click',function(event) {
var string = "helloWorld";
$.ajax({
url: "/test/test_page/?id="+string,
type: "POST",
dataType: "text",
success: function(){
alert('Saved Successfully');
},
error:function(){
alert('Error');
}
});
});
</script>
In routes.rb I have defined the following route:
post 'test/test_page/:id', to: 'pages#test_page'
However, when I press the button I get the defined error-alert and upon inspecting the browser console I see the following error:
jquery.js:11007 POST https://my-website.com/test/test_page/?id=halloWelt 404 (Not Found)
But I can see that "rake routes" shows that the following route is defined:
POST /test/test_page/:id(.:format) pages#test_page
I have tried defining another method in the controller and rerouting, however the 404 error still remains. What can I do to fix this 404 error?
Upvotes: 0
Views: 362
Reputation: 12203
If you're looking to pass the :id to that route, you can use the following url: https://my-website.com/test/test_page/halloWelt
. (i.e. "/test/test_page/" + string
)
I believe in your AJAX, for a POST request, if you want to pass any other data you should explicitly pass in the data like below, rather than via url parameters.
$.ajax({
url: "/test/test_page/" + string,
type: "POST",
data: { hi: 'there' },
...
Upvotes: 2