Jump to content

[SOLVED] Mixing PHP and JavaScript


28rain

Recommended Posts

I have a list of names in a javascript file, and I want the names to be inputted by PHP...

This is the javascript:

function StateSuggestions() {
    this.states = [
			   
        "Alabama", "Alaska", "Arizona", "Arkansas",
        "California", "Colorado", "Connecticut",
        "Delaware", "Florida", "Georgia", "Hawaii",
        "Idaho", "Illinois", "Indiana", "Iowa",
        "Kansas", "Kentucky", "Louisiana",
        "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", 
        "Mississippi", "Missouri", "Montana",
        "Nebraska", "Nevada", "New Hampshire", "New Mexico", "New York",
        "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", 
        "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota",
        "Tennessee", "Texas", "Utah", "Vermont", "Virginia", 
        "Washington", "West Virginia", "Wisconsin", "Wyoming"  
    ];
}

 

And I want to make a list of names similar using:

 

while ($row = mysql_fetch_array($result)) {
$name=stripslashes($row['name']);
$display_block.="\"$name\", ";
}

 

Excetra excetra and i want $display_block to be echo'd into that javascript file...

Any help please (Oh and i have never used javascript before!)

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/172854-solved-mixing-php-and-javascript/
Share on other sites

$display = "<script type='text/javascript'>\n";
$display .= "jsArray = new Array();\n";
$count = 0;
while ($row = mysql_fetch_array($result)) {
$name=stripslashes($row['name']);
$display .= "jsArray[".$count."] = '".$name."';\n";
$count++;
}
$display.= "</script>";

echo $display;

PHP code

while ($row = mysql_fetch_array($result))
{
    $states[] = '"'.stripslashes($row['name']).'"';
}
$jsStateList = implode(',', $states)

 

Where you create the js code

function StateSuggestions() {
    this.states = [
<?php echo wordwrap($jsStateList);?>
    ];
}

On a second look, stripslashes() will un-escape single quotes in the content. But, if the content has a double quote your javascript will fail (becuase the js elements are defined with double quotes). I would suggest not using strpslashes and defining the javascript elements with single quotes - that way the escaped single quotes will be needed:

 

PHP code

while ($row = mysql_fetch_array($result))
{
    $states[] = "'{$row['name']}'";
}
$jsStateList = implode(',', $states)

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.