Check on the PHP side
Based on the present code in the question, the simplest is to check the content of the variables with PHP, thus preparing the value to be used by JavaScript on the client side:
if (is_null($string_patr)) {
$vv_patr = $string_seri;
}
else {
$vv_patr = $string_patr.','.$string_seri;
}
echo '
<script type="text/javascript">
var vv_patr = "'.$vv_patr.'";
alert(vv_patr);
</script>';
Example on Ideone .
In this way PHP checks the variables and when it is to send the JavaScript code to the browser, it goes less code and is ready to be used.
Learn more about PHP's is_null()
function.
Check on the JavaScript side
To keep your code with logic on the JavaScript side, you'll need to change the way you check the contents of the variable.
The null
in the PHP variable will reflect nothing in the JavaScript variable.
$string_patr = null;
$string_seri = "bubu";
print("<SCRIPT language=javascript>
string_patr = \"$string_patr\";
string_seri = \"$string_seri\";
if(string_patr == null){
vv_patr = string_seri;
}
else{
vv_patr = string_patr+','+ string_seri;
}
alert(vv_patr);
</SCRIPT>");
Will result in:
<SCRIPT language=javascript>
string_patr = "";
string_seri = "bubu";
if(string_patr == null){
vv_patr = string_seri;
}
else{
vv_patr = string_patr+','+ string_seri;
}
alert(vv_patr);
</SCRIPT>
Notice that null
on the PHP side turned out to be nothing on the JavaScript side. Since you have double quotation marks, you end up with string_patr = "";
which allows you to change the check to:
if ((!string_patr || string_patr.length === 0) {
vv_patr = string_seri;
}
else {
vv_patr = string_patr+','+ string_seri;
}
So we're seeing if the variable actually exists and is not empty.
Note: The type of verification depends on what is expected to be in the variable, in the suggested check above you are checking whether it is null
, undefined
or empty. p>