php + ajax
Pessoal,Estou com algumas duvidas com php e ajax..Peguei um codigo(estado+ cidade) de um colunista o imasters... Fiz algumas modificações...Agora o codigo faz o seguinte:Implementei uma busca. onde o usuario seleciona um item da combo e o resultado da ação aparece em um campo text!!To com uma duvida....Tenho dois campos do tipo texto, mas so estou conseguindo carregar os dados em um...Tá acontecendo o seguinte erro:
Erro: item.getElementsByTagName("crm")[1] has no propertiesArquivo-fonte: http://localhost/sigex/servicos/medico.jsLinha: 64
Alguem sabe o que está acontecendo??Também gostaria dá opnião de vcs sobre o codigo!! É mesmo desta maneira que se implementa ajax com php?? segue abaixo o codigo:o formulario<html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>Cadastro</title><link href="css/formatamenu.css" rel="stylesheet" type="text/css"><link href="css/index.css" rel="stylesheet" type="text/css"><script type="text/javascript" src="servicos/medico.js"></script><script language=JavaScript type=text/JavaScript>function MM_reloadPage(init) { //reloads the window if Nav4 resized if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) { document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }} else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();}MM_reloadPage(true);</script><?php include "menu.js"; ?><style type="text/css"><!--body { margin-top: 0px; margin-left: 0px; margin-right: 0px; margin-bottom: 0px;}--></style></head><body ><?php include "menusuperior.php"; ?><form name= "form" action="formMedico.php" method="post" onKeyPress="return entsub(event);" onSubmit="return verifica(this)" enctype="multipart/form-data" ><br> <table width="95%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="73%" valign="top"><table width="88%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="29%" height="30" align="center" valign="middle" class="titulotabela">GERENCIAR MÉDICOS </td> <td width="71%" align="right"><?php $hora = date("H:i"); ?> <input type="submit" name="btn_inserir" <?php if($hora > '13:30' && $_SESSION['funcao'] == 1 )echo 'disabled'; ?> id="btn_inserir"value="Inserir" /> <input type="submit" name="btn_excluir" id="btn_excluir" value="Excluir" /> <input type="submit" name="btn_alterar" id="btn_alterar" value="Alterar" /> <input type="button" name="btn_limpar" id="btn_limpar" value="Limpar" onClick="limpa()" /></td> </tr> <tr> <td class="celulacontornosupesquerdo"> </td> <td class="celulacontornosup"> </td> </tr> <tr> <td colspan="2" class="celulaconteudotable">Para Excluir ou alterar informações, selecione o MÉDICO desejado no campos abaixo:<br> <select name="medico" class="campoform" id="medicos" onChange="Dados(this.value);" onkeypress="cbboxSearch(this, event); return false;" > <?php include "Connections/conexao.php"; $query = "select nome,codmedico from tb_medico order by nome asc"; $resposta= mysql_query("$query"); while ($dados=mysql_fetch_array($resposta)) { if ($_GET['medico'] == $dados['codmedico']) { $selected = 'selected'; $ha = 1; } else { $selected=''; } $saida .= '<option value="'.$dados['codmedico'].'" '.$selected.'>'.$dados['nome'].'</option>'; } echo '<option '.(($ha)?'':'selected').'>Selecione um nome</option>'.$saida; mysql_close($connect);?> </select></td> </tr> <tr> <td colspan="2" class="celulaconteudotable"> </td> </tr> <tr> <td colspan="2" class="celulaconteudotable">Para incluir um novo MÉDICO no sistema ou alterar os dados atuais, edite os campos abaixo:</td> </tr> <tr> <td colspan="2" class="celulaconteudotable"> </td> </tr> <tr> <td colspan="2" class="celulaconteudotable">Nome do Médico:<br> <input name="nome" id= "nomes" type="text" class="campoform" size="50" maxlength="50" value </td> </tr> <tr> <td colspan="2" class="celulaconteudotable">CRM:<br> <input name="crm" type="text" class="campoform" size="14" maxlength="14"value="<?php echo $cr;?>"></td> </tr> <tr> <td colspan="2" class="celulaconteudotable"><input type="hidden" name="ResponsavelCadastro" value = "<?php echo $_SESSION['usuario'];?>"> <input type="hidden" name="DataCadastro" value ="<?php echo date("Y-m-d") ?>"> </td> </tr> <tr> <td colspan="2" class="celulaconteudotableinf"> </td> </tr> <tr> <td height="30" colspan="2" align="right" ><label></label> <?php $hora = date("H:i"); ?> <input type="submit" name="btn_inserir" <?php if($hora > '13:30' && $_SESSION['funcao'] == 1 )echo 'disabled'; ?> id="btn_inserir"value="Inserir" /> <input type="submit" name="btn_excluir" id="btn_excluir" value="Excluir" /> <input type="submit" name="btn_alterar" id="btn_alterar" value="Alterar" /> <input type="button" name="btn_limpar" id="btn_limpar" value="Limpar" onClick="limpa();" /> </span></td> </tr> </table> <br> <br> <br> <br> </td> <td width="15%" valign="top"><table width="90%" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#E6EBF0" class="tabeladedicas"> <tr> <td> <p>Campos Obrigatórios para Preenchimento: Nome do Médico.</p></td> </tr> </table></td> </tr> </table> </form> </body></html> medico.jsfunction Dados(valor) { //verifica se o browser tem suporte a ajax try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); } catch(ex) { try { ajax = new XMLHttpRequest(); } catch(exc) { alert("Esse browser não tem recursos para uso do Ajax"); ajax = null; } } } //se tiver suporte ajax if(ajax) { ajax.open("POST", "medico.php", true); ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.onreadystatechange = function() { //enquanto estiver processando...emite a msg de carregando if(ajax.readyState == 1) { // idOpcao.innerHTML = "Carregando..."; document.getElementById("nomes").innerHTML = "Carregando..."; } //após ser processado - chama função processXML que vai varrer os dados if(ajax.readyState == 4 ) { if(ajax.responseXML) { processXML(ajax.responseXML); } } } //passa o código do estado escolhido var params = "medico="+valor; ajax.send(params); } } function processXML(obj){ //pega a tag medico var dataArray = obj.getElementsByTagName("medico"); //total de elementos contidos na tag cidade if(dataArray.length > 0) { //percorre o arquivo XML paara extrair os dados for(var i = 0; i < dataArray.length; i++) { var item = dataArray[i]; //contéudo dos campos no arquivo XML var descricao = item.getElementsByTagName("nome")[0].firstChild.nodeValue; var crm = item.getElementsByTagName("crm")[1].firstChild.nodeValue; //finalmente adiciona o novo elemento document.forms[0].nome.value = descricao; document.forms[0].crm.value = crm; } } else { //caso o XML volte vazio, printa a mensagem abaixo // idOpcao.innerHTML = "Selecione um Material"; } }medico.php<?//CONECTA AO MYSQL require_once("Connections/conexao.php"); //RECEBE PARÃMETRO $pMedico = $_POST["medico"]; //QUERY $sql = " SELECT nome, crm FROM tb_medico where codmedico ".$pMedico." ORDER BY nome"; //EXECUTA A QUERY $sql = mysql_query($sql); $row = mysql_num_rows($sql); //VERIFICA SE VOLTOU ALGO if($row) { //XML $xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"; $xml .= "<medicos>\n"; //PERCORRE ARRAY //for($i=0; $i<$row; $i++) { // $codigo = mysql_result($sql, $i, "id_cidade"); // $descricao = mysql_result($sql, $i, "dsc_cidade"); while ($dados=mysql_fetch_array($sql)){ $nome = $dados['nome']; $crm = $dados['crm']; $xml .= "<medico>\n"; $xml .= "<nome>".$nome."</nome>\n"; $xml .= "<crm>".$crm."</crm>\n"; $xml .= "</medico>\n"; }//FECHA FOR $xml.= "</medicos>\n"; //CABEÇALHO Header("Content-type: application/xml; charset=iso-8859-1"); //FECHA CONEXAO mysql_close($connect);}//FECHA IF (row) //PRINTA O RESULTADO echo $xml; ?>Discussão (5)
Carregando comentários...