0

I have a funny issue. For some reason on Safari browser the javascript Logic Gates are not working properly. Here is a breakdown:

This whole script is being called with $(#id).load(my/script.php) function

I create a clean vairable.

$perm = $_POST['permission'].

I create html variable

$html_content .= " <div id='bsid_$account_id' onclick="bsview(id)"></div>

I echo the html

<?=$html_content?>

Based on permission ai change the functionality of bsview function i applied in my div.

if ("<?=$perm?>" != "user"){
  function bsview(id) {
    console.log('manager');
  } 
}else{
 function bsview(id) {
    console.log('user_view');
 }
}

Then something funny happens. After checking in Chrome, IE, and Firefox I confirm that the code is working. However when I run the code in Safari the logic gate that should return "TRUE" this permission doesn't equal 'user', instead returns FALSE. This is code echoed into my Safari debugging thinger.

if ("manager" !== "user"){
  console.log('manager');

  function bsview(id) {
    console.log('manager');
  }

}else{
  function bsview(id) {
    console.log('user_view');

  }
}
</script>

And of course it console logs 'users_view'

Ok. If anyone has any insight or criticism for my crappy code please send them my way. I would love to know why this is happening, and how to avoid this same thing from happening.

Thomas Valadez
  • 1,697
  • 2
  • 22
  • 27
  • You can't conditionally define function declarations in Javascript. Function declarations are hoisted to the containing function level scope so both of yours are defined, but since they have the same name, the last one takes precedence. As Barmar shows, you can use a function assignment. – jfriend00 Aug 26 '16 at 23:30

1 Answers1

2

According to

Function declarations inside if/else statements?

it's not valid to put function declarations inside if/else. You should declare the function name outside the if, and then assign to it.

var bsview;
if ("<?=$perm?>" != "user"){
  bsview = function (id) {
    console.log('manager');
  } 
}else{
 bsview = function (id) {
    console.log('user_view');
 }
}

Or you could simplify it to:

function bsview(id) {
    console.log('<?= $perm == "user" ? 'user_view' : 'manager' ?>');
}
Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks. I figured I would have to do that. I just didn't know the reason Safari would react differently. Thanks for the help. – Thomas Valadez Aug 27 '16 at 23:00