将javascript var分配给php返回

Is it possible to assign a php return to a js variable? ex:

<script type='text/javascript'>
var h = <?php include'dbconnect.php';
    $charl = (some number from another sql query)
    $sql=mysql_query("selct type from locations where id='$charl'");
    echo $sql; ?> ;
if(h == "hostile") {
    (run some other js function)
}
</script>

what I need to do is get a single text value (type) from the charl (character location) and assign it to a java script variable and run an if statement on it. any hints?

Here is an update on my code. it doesnt return any errors but its not outputting the way i want it to. it should return the [type] only which should be equal to hostile, city, farm, and stuff like that.it wont run unless the entire string is in the same line. I believe its returning the entire string and not just the echo (like i need it to)

function check_hostile() { var h = '<?php session_start(); include"dbconnect.php"; $charid=$_SESSION[\'char_id\']; $charloc=mysql_fetch_array(mysql_query("select location from characters where id=\'$charid\'")); $charl=$charloc[\'location\']; $newloc=mysql_fetch_array(mysql_query("select type from locations where id=\'$charl\'")); echo $newl[\'type\']; ?>'; 
if(h == "hostile") { 
 if(Math.random()*11 > 8) { 
  find_creature(); 
 } 
}
$("#console").scrollTop($("#console")[0].scrollHeight);
}

Here is the output of an alert function when theis is run.

<?php session_start(); include"dbconnect.php"; $charid=$_SESSION['char_id']; $charloc=mysql_fetch_array(mysql_query("select location from characters where id='$charid'")); $charl=$charloc['location']; $newloc=mysql_fetch_array(mysql_query("select type from locations where id='$charl'")); print $newloc['type']; ?>

Change it to this

var h = <?php include "dbconnect.php";
$charl = (some number from another sql query)
$sql=mysql_query("selct type from locations where id=$charl");
$row = mysql_fetch_row($sql);
echo json_encode($row["type"]); ?>;

json_encode() will convert a PHP value into a valid Javascript representation that you can inject into your script.

Yes, it is possible and is quite a common practice.

But your code has a small issue, it returns a string, so you must enclose it in quotes in javascript.

I have updated your code to fix that small issue and improve the code readability:

<?php 

include'dbconnect.php';
$charl = (some number from another sql query)
$sql=mysql_query("select type from locations where id='$charl'");

if (mysql_num_rows($sql) > 0) {
    $row = mysql_fetch_array($sql);
    $h = $row['type'];
} else {
    $h = null;
}

?>

<script type='text/javascript'>

var h = '<?php echo $h; ?>';
if(h == "hostile") {
    (run some other js function)
}

</script>