Hi

what i want to do is pass a php variable in a script i've already got a drop down list
now what i want to do is as soon as you click on any province in the drop down menu the cities appear in the text area. what is happening now iz i have to put the id in the writeclass function which iz kinda not what i want.

heres the code of the funtion

<form name="myform">

        <select name = "province" onChange="onChangeDropBox();"> 
        <? populateDropBox(); ?>     
        <textarea name ="textArea" readonly="true"></textarea>     
        </form>      
<script type="text/javascript">
function onChangeDropBox()

    {
        var selected =0;
        selected = document.myform.province.value;                  

        var t = "<? writeCities(9);?>";
        document.myform.textArea.value = t;

        }
</script> 

thanxx in advance!!!!

Dani AI

Generated

For : the simplest, reliable pattern is an endpoint that returns the cities for a given province id, and a small client-side call that updates the textarea on change. This keeps PHP on the server and JavaScript in the browser, avoids hard-coding ids into rendered JS, and works well whether the cities are stored as a CSV in one column or as rows in a cities table.

Example server endpoint (returns JSON, use PDO or mysqli rather than deprecated mysql_* functions):

<?php
// getcities.php
if (!isset($_GET['id'])) { http_response_code(400); exit; }
$id = (int)$_GET['id'];

$pdo = new PDO('mysql:host=localhost;dbname=msansi;charset=utf8', 'root', '');
$stmt = $pdo->prepare('SELECT cities FROM provinces WHERE id = :id');
$stmt->execute([':id' => $id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

$cities = [];
if ($row && $row['cities'] !== null) {
  // if stored as a CSV string:
  $cities = array_map('trim', explode(',', $row['cities']));
  // or if normalized, fetch rows from a cities table instead
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode($cities);

Client-side: call that endpoint on change and populate the textarea (modern fetch API):

function onProvinceChange(id) {
  var ta = document.querySelector('textarea[name="textArea"]');
  if (!id) { ta.value = ''; return; }
  fetch('getcities.php?id=' + encodeURIComponent(id))
    .then(r => r.json())
    .then(list => { ta.value = list.join('\n'); })
    .catch(e => { console.error(e); ta.value = 'Error loading cities'; });
}

Use the select like: <select name="province" onchange="onProvinceChange(this.value)">. As mentioned, preloading JS arrays is an option for tiny datasets, but AJAX (as shown) is better for scalability. Troubleshooting tips: check the browser console and Network tab for the request/response, ensure Content-Type: application/json, use prepared statements to avoid injection, and remove the submit button if updates should be immediate. As noted earlier, post formatted code when asking follow-ups so others can read it easily.

Recommended Answers

All 7 Replies

Member Avatar for Member #120589

This usually requires Ajax.

Either that or you create javascript arrays of data via php before the page displays.

<script type="text/javascript">
//place data into js from php 
var myCities=new Array(<?php echo $arr_city;?>);
</script>

thanxx ardav i'll try it out, but i dont want to use ajax, thanxx alot for your interest!!!

ardav i've changed my mind now i think i'll go with ajax ive already created a submit button for the drop down i have never used ajax before but i saw a similar code at w3 schools but i need guidane on how i'm going to about implementing this code.

here's my code again

function writeCities($id)
{       
    $con = mysql_connect("localhost","root","");
    if (!$con) die('Could not connect: ' . mysql_error());
    mysql_select_db("msansi", $con);
    $query  = "SELECT cities FROM provinces WHERE id =";
    $query .= $id;
    $result = mysql_query($query);          

    $row = mysql_fetch_array($result);
    echo $row[0];       
}



function populateDropBox()
{
    $con = mysql_connect("localhost","root","");
    if (!$con) die('Could not connect: ' . mysql_error());
    mysql_select_db("msansi", $con);
    $result = mysql_query("SELECT id,title,cities FROM provinces");

    while($row = mysql_fetch_array($result))
    {   
        echo "<option value=$row[0]>" . $row['title']."</option>";
    }
}
?>

<form name="myform">

    <select name = "province" onChange="onChangeDropBox();"/> 
    <? populateDropBox(); ?>     
    <input type="submit" value ="submit";>     
    </form>    

the ajax code is this

function showCustomer(str)
{
var xmlhttp;
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getcustomer.asp?q="+str,true);
xmlhttp.send();
}

and its output is this when a custumer is selected from the drop menu and its in a table

CustomerID  ALFKI 
CompanyName Alfreds Futterkiste 
ContactName Maria Anders 
Address         Obere Str. 57 
City            Berlin 
PostalCode  12209 
Country         Germany 

your help will be highly appreciated!!!

Member Avatar for Member #120589

CODE tags please. Can't read it.

ok heres the code for my drop down and my submit button

<head><title><?php echo $title;?></title>

<h1><?php echo $heading;?></h1>





</head>

<body>


<?
	function writeCities($id)
	{		
		$con = mysql_connect("localhost","root","");
		if (!$con) die('Could not connect: ' . mysql_error());
	  	mysql_select_db("msansi", $con);
		$query  = "SELECT cities FROM provinces WHERE id =";
		$query .= $id;
		$result = mysql_query($query);			
				
		$row = mysql_fetch_array($result);
		echo $row[0];		
	}
	


	function populateDropBox()
	{
		$con = mysql_connect("localhost","root","");
		if (!$con) die('Could not connect: ' . mysql_error());
	  	mysql_select_db("msansi", $con);
		$result = mysql_query("SELECT id,title,cities FROM provinces");
		
		while($row = mysql_fetch_array($result))
		{	
		    echo "<option value=$row[0]>" . $row['title']."</option>";
		}
	}
?>
 
	<form name="myform">
	
		<select name = "province" onChange="onChangeDropBox();"/> 
		<? populateDropBox(); ?> 	
		<input type ="submit" value="submit";/>   
		</form>	  	


	  
	  
	  
</body>

///////////////////////////////////////////////////////////////////////////////////
and the code from w3 schools is this
which is Ajax and outputs the table in the previous message when a customer is chosen from a drop down menu

function showCustomer(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getcustomer.asp?q="+str,true);
xmlhttp.send();
}

I hope i did enough to let you see!!!

You need to type [code=language] for code tags, kgizo ;-)

Additionally, you might want to try asking in the JavaScript / DHTML / AJAX Forum. You're more likely to get an answer there than in the PHP forum

Member Avatar for Member #120589

[ CODE ] tags!!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.