topher
topher

Reputation: 301

Pass boolean from rails controller to javascript for use in conditional

I have a form in a bootstrap modal that is being processed using ajax. If the form validates it closes the modal or shows the validation errors as expected. However, I would like to redirect the user after the modal hide animation is finished if a condition is met based on a boolean held in the controller. Although the conditional wouldn't work as written, it lets you see what it is I am trying to accomplish:

$(document).ready(function() {
  $('#modal-window').modal({remote: true});
  $('#modal-window').modal('show');
  $('#modal-window').on('hidden', function(){
    var saved = <%= @bool %>;
    if(saved == "true"){
      $(window.location.replace("<%= some_url %>"));}
    });
})

Upvotes: 3

Views: 2653

Answers (3)

kr1
kr1

Reputation: 7485

You're setting saved to a boolean (probably - whatever is in your @bool var)

var saved = <%= @bool %>;

but then compare to the string "true"

if(saved == "true"){

so, if you replace the second line with

if(saved){

it'll work

Upvotes: 3

shweta
shweta

Reputation: 8169

replace

var saved = <%= @bool %>;

with

var saved = "<%= @bool %>";

Upvotes: 1

kobaltz
kobaltz

Reputation: 7070

Where do you have this code posted? If your form is under index.html.erb then when using remote: true, you will want to have a index.js.erb file that will serve the javascript that you're looking to run in your example. Also, don't forget to escape the return URL with j like <%=j some_url %>.

Upvotes: 0

Related Questions