beewuu beewuu - 23 days ago 6
Ruby Question

if else statement appears to run both

In my js erb file, both of my flash message is showing when only one should be. The ajax runs fine and my response is what it is supposed to be. However, for some reason, my flash message takes on the message in both the if and else statement. I put a debugger right before the if statement to test my response and it should've evaluated to true.

$.ajax({
url: '/purchases/options',
method: 'post',
dataType: 'json',
data: data
}).done(function(response){
if(response.duplicate === "true"){
<% flash.now[:alert]= 'This Addressi Is Already In Your Cart Or In Your Report Section.' %>
}
else{

<% flash.now[:notice]= 'Searchs result is added to your cart' %>
}
});
$("<%= j render(:partial => 'layouts/messages') %>").insertBefore('form')[0];

Answer

Since ERB is always going to get interpolated before it's sent to the browser, your browser is basically going to see this:

if(response.duplicate === "true") {
} else {
}

And your server is going to see this:

flash.now[:alert]= 'This Addressi Is Already In Your Cart Or In Your Report Section.'
flash.now[:notice]= 'Searchs result is added to your cart'

This basically means your server will always run both of those flash lines.

What you'll need to do, is move everything into the JS file without ERB's help, and manually set the flash text there.

For example, lets say you have the following markup on your page somewhere, that will be the "placeholder" for the flash text:

<div id="flash"></div>

Then in JavaScript, you'll just set the text manually:

$("<%= j render(:partial => 'layouts/messages') %>").insertBefore('form')[0];

$.ajax({
  url: '/purchases/options',
  method: 'post',
  dataType: 'json',
  data: data
}).done(function(response){
  if (response.duplicate === "true") {
    $("#flash").text("This Addressi Is Already In Your Cart Or In Your Report Section.");
    $("#flash").addClass("alert");
  } else{
    $("#flash").text("Searchs result is added to your cart");
    $("#flash").addClass("notice");
  }
});