I am fairly new to Rails and Haml. I am trying to have a button in my view that holds a "key" parameter which will pass that same parameter and trigger a method in the controller using jQuery with Ajax.
Everything can be done behind the scenes in my other class (it's a POST REST request) and I don't need to view anything other than a success message. I have debugged all the variables and the routes, however, the Ajax is not catching the key: parameter
for some reason. It keeps saying undefined
. I tried to hardcode the key
parameter in the controller method and everything else is confirmed working but just missing the parameter.
In my view I have this line:
%button#start{ key: @start_key }= start
In my process.js file:
$(document).ready(function(){
$('button#start').on('click', function(){
var start_key = $('button#start').attr('key'); <------------
$.ajax({
url: '/process/start_process',
data: start_key
})
$('#started_msg').text('started !!!');
});
});
In my controller.rb, I have this method:
def start_process
Client.start_process(params[:key])
End
I wasn't sure if this is the correct way to do this. Please feel free to give me some comments or whether there is additional information needed.
You're missing a few bits, see inline comments.
$(document).ready(function(){
$('button#start').on('click', function(){
var start_key = $('button#start').attr('key');
$.ajax({
url: '/process/start_process',
method: 'POST', // <-- POST instead of GET
data: { // <-- POST an object instead of just the value
key: start_key // <-- named param
}
})
$('#started_msg').text('started !!!');
});
});
Before when you were just sending back the key "bare", the params array would have looked like this:
{"my-key-value"=>nil}
Now that you post an object back to the rails app, the params hash should contain the key "key", and the right value, eg:
{key: "my-key-value"}
If you look at your rails server request logs you should be able to see the differences. It lists the request parameters (at least rails 4 does and I think rails 3 did too).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.