In order to better meet your needs, ie to retrieve the value according to the product selected in the select
field, I will present the following solution:
Make sure that when the value of select
is changed, an event is created that triggers a request that returns the value of the product in JSON format.
Follow this approach:
<?php
$sql = "SELECT * FROM servicos ORDER BY nome";
$resultado = mysql_query ($sql) or die ("Problema na lista!");
?>
<select name='servico' id="idservico" style="text-transform:uppercase">
<option value=''> Selecione</option>
<?php while ($servico = mysql_fetch_object($resultado)): ?>
<option value="<?php echo $servico->id?>"> <?php echo $servico->nome?> </option>
<?php endwhile ?>
</select>
<br />
<input name="valor" type="text" id="idvalor" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script><scripttype='text/javascript'>$(document).ready(function(){//alteravalordocampofunctionalteraValorCampo(){varidservico=$("#idservico" ).val();
var data = {
"action": "obtervalor",
"idservico" : idservico
};
data = "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "obtemvalor.php",
data: data,
success: function(data) {
$("#idvalor").val(data.valor);
}
});
return false;
}
$( "#idservico" ).change( alteraValorCampo );
alteraValorCampo();
});
</script>
Now, let's create the obtemvalor.php
file that will be responsible for retrieving the value of the selected product in the select
field.
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checa se valor existe
$action = $_POST["action"];
$id = $_POST['idservico'];
switch($action) {
case "obtervalor": obter_valor_servico($id);
break;
}
}
}
//Funcao que checa se a requisicao ajax e valida.
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function obter_valor_servico($id){
$sql = "SELECT id, valor FROM servicos WHERE id = ".intval($id);
$resultado = mysql_query ($sql) or die ("Problema na lista!");
$linha = mysql_fetch_object($resultado);
echo json_encode($linha);
}
?>
In this way, whenever a service is selected, the value field will receive the value of the service.
Technologies used for solution: Jquery , PHP and AJAX .