-1

So, I have this code.

$url = "www.google.com";
<script>
    $( document ).ready(function() {
     alert(<?=$url?>);
    }); 
</script> 

Sometimes this variable will be empty depending of what section of the page is loaded. The page that should echo the url is section 2 but not section three. The jquery code is set at the footer of the page. My knowledge of php is very limited, so I am wondering if I should set the variable to null or '' so that if it is empty it is "defined?". I could use the isset, but that is not an option.

$url = '';
$url = "www.google.com";
<script>
    $( document ).ready(function() {
     alert(<?=$url?>);
    }); 
</script>

The code that loads the sections looks someting like this.

if(condition1){

} elseif(condition2){
    $url = "www.google.com";
}else{


}
Divern
  • 343
  • 2
  • 15

1 Answers1

0

Actually it looks like you don't need PHP involved at all, as you are talking about "what section of the page is loaded", so surely you could get the position on page using javascript, such as here: How to get the anchor from the URL using jQuery?

Otherwise, if the page is being built by PHP prior to output, then why can't you use isset?

$url = "www.google.com";
<script>
    $( document ).ready(function() {
     alert(<?php 
if (isset($url) && !empty($url)){ echo $url;} ?>);
    }); 
</script> 
Onyx
  • 876
  • 1
  • 10
  • 18
  • If you are checking for `!empty` you do not need to check for `isset`. – kojow7 Sep 27 '17 at 03:02
  • If (!empty($url)){echo: $url;}else{} like this? @kojow7 – Divern Sep 27 '17 at 03:04
  • @Divem, while I do not fully understand what your code was trying to accomplish, yes, `!empty` by definition also checks `isset`, so it is redundant to include it again. – kojow7 Sep 27 '17 at 03:06
  • 1
    @kojow7 : True, this message was brought to you by the Department of Redundancy Department. – Onyx Sep 27 '17 at 03:27