0

All the other solutions in stackoverflow doesn't seem to work for me so i'm posting my code for assistance. I want to output the variable: @less_per_unit via jquery

Here is my tag inside _form.html.erb:

<script>
$(document).on('keyup', ".input-quantity", function(){ 
  $.ajax({
      url:  "/so_check_increment",
      type: "GET",
      data: { quantity: $(this).val(), product_id: $(this).closest('tr').find('.input-product_code').val()}
  }); 
    $(this).closest('td').next('td').find('.increment').text('<%== j @less_per_unit%>');
}); 
</script>

And here is my controller:

  def check_increment
    @less_per_unit = "testing"
  end

I know that the ajax works, i've also set up the routes. If I try binding.pry, I know that rails can find @less_per_unit, but I can't output it with javascript.

1 Answer 1

1

This is not working because:

Let us say this form is rendered in action 'new' of controller 'Post', then @less_per_unit needs to be initialised there to use it in the view file of that action which you are using. Where as you are using an AJAX call and during that call, you are defining an instance variable which will definitely be not accessible to the already rendered html file.

So, you need to return JSON data from your check_increment action and receive that data in AJAX call response and then use it.

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

15 Comments

Actually j is rails code for “escape javascript”. I learned that from the other stack overflow questions similar to mine. I tried removing the extra = and j but it still doesnt work.
Okay. I didn't know that. But why an extra '='. As per documentation, <%= j @less_per_unit %> should work fine.
I tried that and it still doesn't show any value. I tried console.log('<%= j @less_per_unit %>') also. No luck.
Isn't it obvious that this will not work? The reason is: Let us say this form is rendered in action 'new' of controller 'xyz', then @less_per_unit needs to be initialised there to use it in the view file of that action which you are using. Where as you are using an AJAX call and during that call, you are defining an instance variable which will definitely be not accessible to the already rendered html file.
So, have you basically understood why your code was not working earlier? I hope you have read the explanation.
|

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.