Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

This question already has an answer here:

I'm trying to pass a string variable from PHP to Javascript and it is giving me troubles.

I actually pas a number variable as per the code below and it works, but once I introduce (or uncomment) the line var cityname = <?=$city;?>; in my javascript code then it doesn't work. I believe it has something to do with the type of data because if I introduce a number like Scity = 3 in my PHP then it works.

Thank you

I have the following PHP:

<?php
    $get_total_rows = 0;
    $city = "London";

    $db = pg_connect("$db_host $db_name $db_username $db_password");
    $query = "SELECT * FROM table";
    $results = pg_query($query);

    $get_total_rows = pg_numrows($results); 
?>

and I have the following javascript:

<script type="text/javascript">
$(document).ready(function() {
var track_load = 0; //total loaded record group(s)
//var cityname = <?=$city;?>;
var total_rows = <?=$get_total_rows;?>;

$('#results').load("autoload_process.php", {'rows':total_rows}, function() {track_load++;}); //load first group
share|improve this question

marked as duplicate by Barmar javascript Apr 21 at 20:58

This question was marked as an exact duplicate of an existing question.

2  
As in most programming languages, javascript expects string literals to be quoted var cityname = '<?=$city;?>'; – Mark Baker Apr 21 at 20:42
1  
@MarkBaker Or better yet, var cityname = <?= json_encode($city) ?>; so it gets escaped if necessary. – ceejayoz Apr 21 at 20:43
    
@MarkBaker thanks, that works – Sam Apr 21 at 20:55

In the case of strings, the content must be between quotes (ex.: val = "content"). Try to do something like this:

var track_load = 0; //total loaded record group(s)
var cityname = "<?php echo $city; ?>"; // string
var total_rows = <?php echo $get_total_rows;?>; // number
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.