简体   繁体   中英

Cannot access Rails variable inside Javascript tag

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.

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.

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