1

I have /map/mappge page already got @name from my index. So my map controller,

class MapController < ApplicationController
  def mappage
    @name = params[:name]
  end

and, I send it by submit tag.

<form action="/map/mappage" method="GET">
   <%= select_tag "univ", "<option selected>selected</option><option value='name1'>name1</option><option value='name2'>name2</option><option value='name3'>name3</option>".html_safe, class:"btn btn-default btn-hg dropdown-toggle" %>
   <%= submit_tag "go", class:"btn btn-success btn-hg" %>
</form>

like this. When I select name1 and submit it, the mappage url looks like

'myhost'/map/mappage?name=name1&commit=go

What I want to do is call ajax while I keep the name parameters. So I call

$(document).ready(function () {
    $("#my_button").click(function () {
        var ajax_name = "<%= @name %>";

        $.ajax({
            url: "/map/mappage",
            type: 'GET',
            data: {
                'name': ajax_name
            },
            success: function (data) {
                alert("good");
            }
        });
    });
});

When I click "#my_button", alert message comes. The thing is, when I click "#my_button", error comes out. @name is nil. And I checked that my url looks like

'myhost'/map/mappage?#

How can I keep @name parameters? Any suggestions, or document that I can read?

Rajan Goswami
  • 769
  • 1
  • 5
  • 17
Changnam Hong
  • 1,669
  • 18
  • 29

2 Answers2

2

A rails way to do this would be to have a form with remote: true, and an endpoint for it (a controller with respond_to :js, and a corresponding .js view).

Pls, let me know if you need this illustrated with some code.

x6iae
  • 4,074
  • 3
  • 29
  • 50
bosskovic
  • 2,034
  • 1
  • 14
  • 29
  • bosskovic is right. setting remote true, and passing your params straight is a great way to achieve what you trying to do. [Check this SO answer on how to do this.](http://stackoverflow.com/a/33468554/4330954) – x6iae Nov 18 '15 at 09:45
0

You can use gem ' gon It seem to be easy way to pass params from controller rails into javascript file via view

huhuhu
  • 201
  • 2
  • 12