简体   繁体   中英

Sending a jQuery variable to Rails controller

I'm trying to get the variable "response.data.uri" from my jQuery to a rails controller, but it isn't working. I can get to the rails controller but the variable isnt there.

jQuery:

function responseCallbackHandler(response) {
   switch (response.status) {
     case 201:
         $.ajax({ url: '#{addbank_bankaccts_path}',
         type: 'POST',
         beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
         dataType: "json",
         data: 'account_uri=' + response.data.uri
         success: function(response) {
           // successfully executed the controller method
           }
         });
         break;
     }
 }

routes.rb:

post "/bankaccts/new" => 'bankaccts#addbank' 

controller:

class BankacctsController < ApplicationController

  def addbank
      @uri = (params['customer_uri'])
      @id = (params['id'])
      @auri = (params['account_uri'])
      # all equal nil ^
      redirect_to root_url
  end

Ah, I know: In ruby, single quotes do not perform variable interpolation. So if you posted the jquery as it appears in the browser, the url for you ajax request would be:

'#{addbank_bankaccts_path}'

...which is gibberish--a browser does not understand ruby or rails. Url's in a browser must look like:

http://mysite.com/js/myjs.js
js/myjs.js

If your jquery is in a file whose name ends with .erb, then before sending the file to the browser rails will execute any ruby code in the file, but single quotes in ruby do not perform variable interpolation. Here is an example of that:

name = 'Dave'
str = '#{name} says hello.'
puts str

--output:--
#{name} says hello

But with double quotes:

name = 'Dave'
str = "#{name} says hello."
puts str

--output:--
Dave says hello.

I don't know if you are coming from a python background or not, where all quotes are equivalent; but in a lot of languages, including ruby, single and double quotes are not equivalent.

Your form_authenticity_token has the same problem:

beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},

Try -

data: {account_uri: response.data.uri, 'customer_uri': SOME_VALUE, 'id': SOME_VALUE}

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