1

So I have this chunk of code on the view:

var variable_test = 'begin';
$.ajax({
  url : "/controller/index",
  type : "post",
  data : variable_test
}).done(function(response) {
  alert('1');
})
    .fail(function (error) {
    alert('2');
});

var eia = <%= @variable.to_json.html_safe %>;
alert(eia);

and on controller I have this:

def index
   @someVariable = 'end'
   @variable = params[:variable_test]
end

on execution this would be the result:

dialog message with 1 (so it was supposed to have worked and posted something)

dialog message with null

and this is the server side POST request:

Started POST ...  
Processing by Controller#index as */*  
Parameters: {"begin"=>nil}  
...  
...  
Current user: anonymous  
...  
Completed 200 OK... 

So what is wrong? Is it actually posting the variable variable_test to controller variable ? If yes, why does it reads it as null? How to fix this?

2 Answers 2

2

It is sending your value in the post. The problem is that data takes an object as value, so if you want to read the value in the server side as params[: variable_test] you need to make the ajax call

var variable_test = 'begin';
$.ajax({
  url : "/controller/index",
  type : "post",
  data : { variable_test: variable_test },
}).done(function(response) {
  alert('1');
}).fail(function (error) {
  alert('2');
});

On another hand, I'm not sure what you are trying to accomplish, The index action as you have it will try to render the index.html.erb file you have under app/views/controller/, is that the same index action that is being called in the ajax request?

Sorry for not commenting, not enough reputation.

Sign up to request clarification or add additional context in comments.

6 Comments

I just want to send info back to server as needed. The way you edited it is still returning null. (and don't mind about not having reputation for comment. I know that situation well.)
after updating data on server I would like to read the new value from client.
When are you getting the alert with null? When you load the page?
I just created an empty app and added some similar code. Check this
If you are getting the null when you load the page that is because it is expecting the variable_test argument to be in the url, something like localhost:3000/?variable_test=ilikepotatoes.
|
1

The way this works is actually quite simple.

Your Ajax seems to be sending your request to your controller:

Started POST ...
Processing by Controller#index as */*
Parameters: {"begin"=>nil}

... it's your response which is not being caught...

#app/assets/javascripts/application.js
$.ajax({
  url : "/controller/index",
  type : "post",
  data : {serialized: "data"}, // data should be serialized
}).done(function(response) {
  alert('1');
}).fail(function (error) {
    alert('2');
});

This setup should trigger the alert('1') function.


Handling the response is where you're falling short:

1. ERB doesn't work in the asset pipeline

#app/assets/javascripts/application.js
var eia = <%= @variable.to_json.html_safe %>; // won't work
alert(eia); // won't work

This will not work.

What will is to use the returned data inside the ajax .done method:

#app/controllers/controller_controller.rb
class ControllerController < ApplicationController
   def index
      @variable = {}
      @variable.attribute = "test"
      respond_to do |format|
         format.json { render json: @variable }
      end
   end
end

#app/assets/javascripts/application.js
$.ajax({
  url : "/controller/index",
  type : "post",
  data : {serialized: "data"}, // data should be serialized
}).done(function(response) {
   json = JSON.parse(response);  
   alert(json.attribute)
}).fail(function (error) {
    alert('2');
});

This should return the data, allowing you to output it into the view

--

2. Use Server-Side JS

In addition to the fact that ERB won't work in the front-end, you'll have to look at how your JS is being called.

You must remember that JS is front-end; it doesn't have any access to your Ruby variables. Thus, if you're trying to access the returned data in your view, you either need to capture the response from the server (#1), or run server-side JS like this:

#app/controllers/controller_controller.rb
class ControllerController < ApplicationController
   def index
      respond_to do |format| 
         format.js #-> calls app/views/controller/index.js.erb
      end 
   end
end

This will invoke index.js.erb whenever you run the index action - allowing you use any of the data you've defined in Ruby:

#app/views/controller/index.js.erb
var eia = <%= @variable.to_json.html_safe %>;
alert(eia);

This would also have to coincide with removing the response hooks in your front-end ajax:

#app/assets/javascripts/application.js
$.ajax({
  url : "/controller/index",
  type : "post",
  data : {serialized: "data"}, // data should be serialized
});

3 Comments

I don't get it yet. 'var something = <%= ATserverVariable %>' Isn't supposed to be processed on server side so it will return a page with that variable value when it was requested? So lets say I post something to 'serverVariable', if someone else request it again, its not supposed to get a new value? I want to update datas on server in a way that the client side can request the new value. Also, you said that 1 - var eia = <%= ATvariable.to_json.html_safe %>; won't work, but that line of code is recovering the proper value of the variable, so why did you say it won't work?
So, what you want is a value to be persisted so future visits see that new value? You will need to start using a database for that, the variables in a controller are not persisted. Also, that line of code works because you have in a view, if you had it .js file in your assets pipeline it won't work (note that he named the file to contain that code app/assets/javascripts/application.js. That's what Rich Peck meant.
JS = client side, Ruby = server side. I can't read Chinese, client-side can't read server-side variables. Two different things; your @variable is a ruby variable, set in the server. That memory is only available to server memory; you cannot load it into JS without "translating" it in ways such as how I've described

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.