Check on the PHP side
Based on the code present in the question, the simplest is to check with PHP the contents of the variables, 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 in Ideone.
This way PHP checks the variables and when is to send the Javascript code to the browser, will less code and already ready to be used.
Learn more about the function is_null()
php.
Check on the Javascript side
To keep your code logical on the Javascript side, you will need to change the way you check the contents of the variable.
The null
in the PHP variable will be reflected in nothingness 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 the null
on the PHP side turned out to be nothingness on the Javascript side. Since you have double quotes, 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 it’s not empty.
Note: The type of check depends on what is expected to be in the variable, in the above suggested check you are checking whether it is null
, undefined
or empty.
what’s the mistake??
– pc_oc
The mistake is that the
if(string_patr == null)
does not recognize whether it is null or not! And it’s all in php'– Alexandre
@Alexandre, prefer [Dit] the question to add information/clarify doubts.
– brasofilo