Jump to content

php + ajax


Recommended Posts

Mais um exempo...

Faz download deste ficheiro http://prototypejs.org/assets/2009/8/31/prototype.js para a pasta onde tens o index.php

Renomeia para "guardar.php" o teu ficheiro que faz a query à base de dados e coloca na mesma pasta onde está o index.php

Esta é uma página HTML com formulário:


<script src="prototype.js" type="text/javascript"></script>

<script type="text/javascript">
function actualizar(elemento, formulario) {
    var dados = {};
    if ($(formulario)) dados = $(formulario).serialize(true);
    new Ajax.Request('guardar.php', {
        method: 'post',
        parameters: dados,
        onSuccess: function (transport) {
            $(elemento).innerHTML = transport.responseText;
        onFailure: function() {
            alert('Erro: Tente mais tarde.')


<div id="resultado"></div>

<form id="formulario" action="#" onsubmit="actualizar('resultado', 'formulario'); return false;">
<input name="login" type="text" value="login de teste" />
<input type="submit" value="enviar" />

A partir daqui podes fazer N chamadas em ajax...

Se quiseres que o resultado apareça noutro elemento DOM ou usar outro formulario, basta chamares actualizar('outro_elemento', 'outro_formulario');

Nota: nos elementos HTML coloca o atributo ID com o nome correcto, senão nada funciona...

Link to comment
Share on other sites

ja agora o que esta mal aqui. Nao preenche o segundo select

function list_dados( valor ){
http.open("GET", "result.php?id=" + valor, true);
http.onreadystatechange = handleHttpResponse;

function handleHttpResponse(){
campo_select = document.forms[1].subcategoria;
if (http.readyState == 4) {
campo_select.options.length = 0;
results = http.responseText.split(",");
for( i = 0; i < results.length; i++ ){
string = results[i].split( "|" );
campo_select.options[i] = new Option( string[0], string[1] );
function getHTTPObject() {
var req;
try {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
if (req.readyState == null) {
req.readyState = 1;
req.addEventListener("load", function () {
req.readyState = 4;
if (typeof req.onReadyStateChange == "function")
}, false);
return req;
if (window.ActiveXObject) {
var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
for (var i = 0; i < prefixes.length; i++) {
try {
req = new ActiveXObject(prefixes[i] + ".XmlHttp");
return req;
} catch (ex) {};
} catch (ex) {}
alert("XmlHttp Objects not supported by client browser");
var http = getHTTPObject();

<h2 style="font-family:verdana; font-weight:bold; font-size:15px;">Fazer um pedido novo</h2>
echo '<form action="#" name="cadastro" method="post" onchange="list_dados( this.value )">';


echo '<tr><td>Ramo: <select name="categoria" onchange="list_dados( this.value )"><option></option>';
      $consulta = mysql_query("SELECT * FROM ramos");

      while( $row = mysql_fetch_array($consulta) )


      echo "<option value=\"{$row['id']}\">{$row['ramo']}</option>";


echo '</select></tr></td><tr><td>subramo: <select name="subcategoria"></select>';
echo '</td></tr>';

header('Content-Type: text/html; charset=ISO-8859-1');

      $con = mysql_connect("localhost", "root", "ripituh");

      $categoria = $_GET["id"];
      $consulta = mysql_query("SELECT * FROM ins_prod WHERE ramo = '$categoria' ORDER BY id ASC") or die ("asdasdsd");

      while( $row = mysql_fetch_assoc($consulta) )

      echo $row["subramo"] . "|" . $row["id"] . ",";

Java, Android developerhttp://minimalcode.net

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.