简体   繁体   中英

Call ruby function through AJAX

I barely know anything about ajax, and I need to use it for my rails application. My function is here (controller function):

def verify_code
  input = params[:input]
  code = params[:code]
  if input == code
    return true
  else
    return false
  end
end

The javascript that I have attempted:

$('#submit_me').click(function() {
  var input_code = $('.input_code').val();
  var bool = $.ajax({
        url: '/verify_code/'+input_code+'/<%= @code %>',
        type: 'get',
        contentType: 'application/json; charset=UTF-8',
     });
  alert(bool)
});

I have idea how to get this ajax going. I am trying to call the controller function and getting the return value to the javascript. Can someone please help me with this? Thanks.

You were almost there! You need to implement the "done" callback (= Javascript function that will be executed on the success of the Ajax request):

Try this:

$('#submit_me').click(function(event) {
  event.preventDefault();
  var input_code = $('.input_code').val();
  $.getJSON('verify_code/'+input_code+'/<%= @code %>').done(function(data){
    alert(data);
  })
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM