After exploring various sources on this subject, I haven't found a satisfactory solution to my specific situation, so I'm reaching out here for help.
Let's start by looking at the code snippet below:
<tr>
<td align="right">Estado</td><td>
<select name="estado" onChange="javascript:Atualiza(this.value,'0');">
<option>[selecione]</option>
<?
$qry = "SELECT nome, uf FROM tb_estados";
$res = mysql_query($qry);
while ($ln = mysql_fetch_array($res)) {
echo "<option value='$ln[uf]'>".$ln['nome']."</option>";
}
?>
</select>
</td>
</tr>
Now, let's move on to this section of the code:
<tr>
<td align="right">Cidade</td>
<td><div id="atualiza"></div></td>
</tr>
The challenge I'm facing involves extracting the value from <div id="atualiza">
, which is not part of the form object like <select name="estado"
. I need to INSERT INTO my database the value within <div id="atualiza">
.
How can I achieve this?
My idea is to store the value in a hidden field and include it in the form submission for insertion into the database.
I have encountered a similar issue before and managed to solve it through unconventional means. However, I believe there must be a simpler approach to tackle this problem.
The Atualiza function
function Atualiza(valor,cid)
{
loadXMLDoc("combo_cidade.php",valor,cid);
}
Additionally, the page combo_cidade.php
<?php
echo "<select name='cidade' id='cidade'>";
echo "<option>[selecione]</option>";
# establish database connection
include_once("config/config.php");
$sql = "SELECT tb_cidades.nome, tb_cidades.id FROM tb_cidades INNER JOIN tb_estados ON tb_cidades.uf=tb_estados.uf WHERE tb_cidades.uf='".$_GET["uf"]."'";
$resultado = mysql_query($sql);
while ($linha = mysql_fetch_array($resultado)){
if ($_GET["cid"]==$linha["id"]){$sel="selected";}else{$sel="";}
echo "<option value='$linha[id]' $sel>$linha[nome]</option>";
}
echo "</select>";
?>
Here is the full script that manages my combo
// JavaScript Document
var req;
function loadXMLDoc(url,valor,cid)
{
req = null;
// Look for native object (Mozilla/Safari)
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url+'?uf='+valor+'&cid='+cid, true);
req.send(null);
// Look for ActiveX version (IE)
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url+'?uf='+valor+'&cid='+cid, true);
req.send();
}
}
}
function processReqChange()
{
// only when state is "completed"
if (req.readyState == 4) {
// check if server returns "OK"
if (req.status == 200) {
// locate div id="atualiza" and insert the returned content as HTML text
document.getElementById('atualiza').innerHTML = req.responseText;
} else {
alert("There was a problem obtaining the data:\n" + req.statusText);
}
}
}
function Atualiza(valor,cid)
{
loadXMLDoc("combo_cidade.php",valor,cid);
}