0

Im trying do build a form using ajax.

I read this tutorial, but it is not clear to me.

I would like to submit a simple form and show the result in the same page without refresh a page. I do not have models in my application. I just wanna submit a form, make a request to a api and show the result back to the page.

If I use this for example:

<form method="post" action="/my_controller/my_action" class="button_to" data-remote="true" data-type="json">
  <input type="text" ..>
  <input type="text" ..>
  <div><input value="Show" type="submit" /></div>
</form>

How can I get this values in my_controller and how can I show back to the view?

Thanks for any help

coffee
  • 3,048
  • 4
  • 32
  • 46

3 Answers3

1

Your form

<form method="post" action="/my_controller/my_action" class="button_to" data-remote="true"       data-type="script">
  <input type="text" name="value1">
  <input type="text" name="value1">
  <div><input value="Show" type="submit" /></div>
</form>

Your display div tag

<div id="feeds"></div>

Your action

def my_action
   @value1 = params[:value1]
   @value1 = params[:value2]
   respond_to do |format|
      format.js
   end       
end

Your view my/my_action.js.erb

$('#feeds').prepend("<%= j ("<p>#{@value1}-#{@value2}</p>") %>");
ibariens
  • 3
  • 2
Muhammet
  • 325
  • 2
  • 9
0

use the ajax method of jquery

$.ajax({
 url:'/path/to/controller',     
 type:'GET',
 data:{formData:$('form').serialize()},
 success:function(data){
 //do what ever with the response
 }

});

additionally you can attach an error event handler

http://api.jquery.com/jQuery.ajax/

Rafay
  • 30,950
  • 5
  • 68
  • 101
0

I've tried to edit the answer of @MuhammetDILEK, which almost worked for me. However, I needed to use data-type="script" instead of data-type="json" in the form, as explained in: https://stackoverflow.com/a/15115551/3472491

Community
  • 1
  • 1
ibariens
  • 3
  • 2