I have the following situation and I know have a lot of this subject here in stackoverflow, but no answers give a real solution, so I'm posting again.
First take a look at this code:
<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>
and Now at this piece of code
<tr>
<td align="right">Cidade</td>
<td><div id="atualiza"></div></td>
</tr>
I have a linked combo, to show states and cities.
Now my problem:
I can not get the value from my <div id="atualiza">
the values of <select name="estado"
no problem cause it is an object of my form but the div tag is not an object of the form.
I need to INSERT INTO
my database the value of <div id="atualiza">
How to do this?
I would like to save the value inside an hidden field and send in my form to insert in my database.
I had a similar situation before and I solved the problem, but it was so bizarre and I know there is an easy way to do that.
The Atualiza function
function Atualiza(valor,cid)
{
loadXMLDoc("combo_cidade.php",valor,cid);
}
Also my page combo_cidade.php
<?php
echo "<select name='cidade' id='cidade'>";
echo "<option>[selecione]</option>";
# my databse 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 goes the whole script that handle my combo
// JavaScript Document
var req;
function loadXMLDoc(url,valor,cid)
{
req = null;
// Procura por um objeto nativo (Mozilla/Safari)
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url+'?uf='+valor+'&cid='+cid, true);
req.send(null);
// Procura por uma versao ActiveX (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()
{
// apenas quando o estado for "completado"
if (req.readyState == 4) {
// apenas se o servidor retornar "OK"
if (req.status == 200) {
// procura pela div id="atualiza" e insere o conteudo
// retornado nela, como texto HTML
document.getElementById('atualiza').innerHTML = req.responseText;
} else {
alert("Houve um problema ao obter os dados:\n" + req.statusText);
}
}
}
function Atualiza(valor,cid)
{
loadXMLDoc("combo_cidade.php",valor,cid);
}
Add this JS code in the page:
<script type="text/javascript">
function AddHiddenValue(oForm) {
var strValue = document.getElementById("atualiza").innerHTML;
var oHidden = document.createElement("input");
oHidden.name = "atualiza";
oHidden.value = strValue;
oForm.appendChild(oHidden);
}
</script>
Then have this in the form tag:
<form ... onsubmit="AddHiddenValue(this);">
And finally read the value of "atualiza" from the request in your PHP code.
In javascript, value
attribute is used in form elements such as input
, select
and textarea
. If you want to get the "value" of a DIV element (I mean what is written inside that tag), you can use the innerHTML
attribute. For example, consider the following HTML:
<div id="d">Hello</div>
Now document.getElementById('d').innerHTML
will return "Hello".
Getting back to your code, when you send the AJAX request, u get a <select name='cidade' id='cidade'>...
text and set that as innerHTML
of the DIV
tag. You can get the selected value in the inner select
using document.getElementById('cidade').value
and set the value of your hidden input
to that value, because when u set that string as the innerHTML
of the DIV
tag, that will be parsed and converted to a normal select
tag inside that DIV
, i.e.
<tr>
<td align="right">Cidade</td>
<td><div id="atualiza"><select name='cidade' id='cidade'><option>...</select></div></td>
</tr>
Conclusion:
Put a hidden input
with name cidade
somewhere inside your form:
<form ...>
...
<input type="hidden" name="cidade" id="cidade_input" value="" />
and set its value when the value of the select
changes:
combo_cidade.php, line 2:
echo "<select name='cidade' id='cidade' onchange='f1(this.value);'>";
in your JavaScript:
function f1(value) {
document.getElementById('cidade_input').value = value;
}
or when the form is submitting:
your form tag:
<form ... onsubmit="f2()">
in JavaScript:
function f2() {
document.getElementById('cidade_input').value = document.getElementById('cidade').value;
}
Some notes on your code:
In your php file combo_cidade.php
, on line 8, you should not use the value given in the request ($_GET) directly. This can lead to a SQL Injection in your code. Instead, you should use addslashes function (or mysql_real_escape_string as highly recommended in the PHP manual) to prevent SQL Injection attacks on your site. That will be like this:
$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='".addslashes($_GET["uf"])."'";
Another note: It is better to use double quotation for HTML attribute values other than single quotes. You can change your second line of PHP code to this:
echo '<select name="cidade" id="cidade" onchange="f1(this.value);">';
And the last note: You don't need to have name
attribute in the echo'ed select
, because it is not in a form and that attribute will be useless. Therefore it will be like this:
echo '<select id="cidade" onchange="f1(this.value);">';
and if you use the onchange
and not onsubmit
(i.e. setting the hidden input
value when the combo changes, not when the form is submitted), the id
attribute is useless too. That will change it to:
echo '<select onchange="f1(this.value);">';
Why don't you put the select in a form? You can have more than one form in a page if you need to.
Try this (in javascript).
var value = document.getElementById("atualiza").firstChild.nodeValue;
or
var value = document.getElementById("atualiza").innerText;
As to how to include that (javascript) into PHP, I'm not in that league (as yet).
Hope this helps.
精彩评论