Pagina 1 di 3 1 2 3 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 21
  1. #1
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    144

    Mandare form con post tramite xml e Ajax

    Ciao a tutti. Non so se questa è la sezione corretta del forum su cui scrivere, spero di si.
    Ho scritto un codice php con anche dell'xml, perchè vorrei ottenere questo risultato:

    http://www.danieletabacco.com/esempi/esempio_php02.php

    Premetto che il codice che scrivo qui sotto l'ho "copiato" dal sito sopra, ma vorrei cambiarlo in modo che invii i dati tramite xml al database e riceva risposta con ajax.(tutto tramite POST perchè deve essere sicuro).
    Ho provato a modificarlo per la mia esigenza ma non funziona perchè non mi fa comparire la tabella con tutti i campi, ma solo la finestra con l'opzione dei nomi.

    il codice originale lo potete trovare qui:
    http://www.danieletabacco.com/18/art...jax-e-php.html

    Cmq per praticità ve lo posto qui sotto comunque...

    provasito.php
    Codice PHP:
    <script type="text/javascript">

    var xmlhttp;

    function mostraInfo(str)
    {
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null)
    {
    alert ("Browser does not support HTTP Request");
    return;
    }
    var url="mostra_utenti.php";
    url=url+"?q="+str;
    url=url+"&sid="+Math.random();
    xmlhttp.onreadystatechange=stateChanged;
    xmlhttp.open("GET",url,false);
    xmlhttp.send(null);
    }

    function stateChanged()
    {
    if (xmlhttp.readyState==4)
    {
    document.getElementById("info").innerHTML=xmlhttp.responseText;
    }
    }

    function GetXmlHttpObject()
    {
    if (window.XMLHttpRequest)
    {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    return new XMLHttpRequest();
    }
    if (window.ActiveXObject)
    {
    // code for IE6, IE5
    return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
    }
    </script>

    <form>
    Seleziona Dipendente:
    <select name="users" onChange="mostraInfo(this.value)">
    <?php

    $db_host 
    "localhost";
    $db_user "administrator";
    $db_password "administrator";
    $db_database "ticket";

    //Seleziono quelli che sono i dipendenti
    $connessione mysql_connect($db_host,$db_user,$db_password);
    mysql_select_db($db_database$connessione);

    $query "SELECT * FROM user ";
    $result mysql_query($query);
    while(
    $riga mysql_fetch_array($result)){
    echo 
    "<option value='$riga[user_id]'>$riga[user_firstname] $riga[user_lastname]</option>";
    }

    ?>
    </select>
    </form>


    <div id="info"></div>

    Codice PHP:

    <?php


    $db_host 
    "localhost";
    $db_user "administrator";
    $db_password "administrator";
    $db_database "ticket";


    $q=$_GET["q"];



    $con mysql_connect($db_host,$db_user,$db_password);
    mysql_select_db($db_database$con);

    $sql="SELECT * FROM dipendenti WHERE id = '".$q."'";

    $result mysql_query($sql);

    echo 
    "<table border='1'>
    <tr>
    <th>Nome</th>
    <th>Cognome</th>
    <th>Anni</th>
    <th>Lavoro</th>
    <th>Stipendio</th>
    </tr>"
    ;

    while(
    $row mysql_fetch_array($result))
    {
    echo 
    "<tr>";
    echo 
    "<td>" $row['user_firstname'] . "</td>";
    echo 
    "<td>" $row['user_lastname'] . "</td>";
    echo 
    "<td>" $row['user_username'] . "</td>";
    echo 
    "<td>" $row['user_password'] . "</td>";
    echo 
    "<td>" $row['user_email'] . "</td>";
    echo 
    "</tr>";
    }
    echo 
    "</table>";

    mysql_close($con);
    ?>








    invece metto il codice dei miei file modificati qui:


    questo file l'ho chiamato: provasito.php

    Codice PHP:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Post</title>
    </head>
    <body>
    <div id="xmldata"></div>
    <script type="text/javascript">
    function readyAJAX() {
    try {
        return new XMLHttpRequest();
    } catch(e) {
        try {
            return new ActiveXObject('Msxml2.XMLHTTP');
        } catch(e) {
            try {
                return new ActiveXObject('Microsoft.XMLHTTP');
            } catch(e) {
                return "A newer browser is needed.";
            }
        }
    }
    }
    var requestObj = readyAJAX();
    var url = "mostra_utenti.php";
    var params = "q=25";
    requestObj.open("POST",url,true);
    requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    requestObj.send(params);
    requestObj.onreadystatechange = function() {
        if (requestObj.readyState == 4) {  
            if (requestObj.status == 200) { 
                alert(requestObj.responseText); 
            } else {
                alert(requestObj.statusText);
            }
        }
    }
    </script>
    <form>
    Seleziona Dipendente:
    <select name="users" onChange="mostraInfo(this.value)">
    <?php

    $db_host 
    "localhost";
    $db_user "administrator";
    $db_password "administrator";
    $db_database "ticket";

    //Seleziono quelli che sono i dipendenti
    $connessione mysql_connect($db_host,$db_user,$db_password);
    mysql_select_db($db_database$connessione);

    $query "SELECT * FROM user ";
    $result mysql_query($query);
    while(
    $riga mysql_fetch_array($result)){
    echo 
    "<option value='$riga[user_id]'>$riga[user_firstname] $riga[user_lastname]</option>";
    }

    ?>
    </select>
    </form>


    <div id="info"></div>
    </body>
    </html>

    questo invece è il file: mostra_utenti.php :


    Codice PHP:
    <?php
    $db_host 
    "localhost";
    $db_user "administrator";
    $db_password "administrator";
    $db_database "ticket";


    $q=$_POST['params'];



    $con mysql_connect($db_host,$db_user,$db_password);
    mysql_select_db($db_database$con);



    $sql="SELECT *
    FROM user 
    WHERE user_id = '"
    .$q."'";

    $result mysql_query($sql);
    if (
    $sql!==false) {echo "non va la query";}

    echo 
    "<table border='1'>
    <tr>
    <th>Nome</th>
    <th>Cognome</th>
    <th>Username</th>
    <th>Password</th>
    <th>Email</th>
    </tr>"
    ;

    while(
    $row mysql_fetch_array($result))
    {
    echo 
    "<tr>";
    echo 
    "<td>" $row['user_firstname'] . "</td>";
    echo 
    "<td>" $row['user_lastname'] . "</td>";
    echo 
    "<td>" $row['user_username'] . "</td>";
    echo 
    "<td>" $row['user_password'] . "</td>";
    echo 
    "<td>" $row['user_email'] . "</td>";
    echo 
    "</tr>";
    }
    echo 
    "</table>";

    mysql_close($con);
    ?>

    Ah, dimenticavo! Ovviamente ho provato con il codice originale e funziona, perciò non è un problema di connessione al database o cose simili ;P


    Qualcuno mi può aiutare???
    Grazie, aspetto con ansia

  2. #2
    Innanzitutto, nel codice che hai modificato non viene creato un file XML come risultato di una query ma quello che viene restituito è plain text.

    Poi ...

    Punto 1:
    nella proprietà onchange del tag select fai riferimento alla funzione "mostraInfo" che nel tuo codice javascript non compare.
    Lo script dovrà quindi essere:
    codice:
    <script type="text/javascript"> 
    function readyAJAX() { 
    try { 
        return new XMLHttpRequest(); 
    } catch(e) { 
        try { 
            return new ActiveXObject('Msxml2.XMLHTTP'); 
        } catch(e) { 
            try { 
                return new ActiveXObject('Microsoft.XMLHTTP'); 
            } catch(e) { 
                return "A newer browser is needed."; 
            } 
        } 
    } 
    } 
    function mostraInfo(data)
    {
    var requestObj = readyAJAX(); 
    var url = "mostra_utenti.php"; 
    
    var params = "q=" + data;
    requestObj.open("POST",url,true); 
    requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    requestObj.send(params); 
    requestObj.onreadystatechange = function() { 
        if (requestObj.readyState == 4) {   
            if (requestObj.status == 200) { 
                alert(requestObj.responseText); 
            } else { 
                alert(requestObj.statusText); 
            } 
        } 
    } 
    }
    </script>
    Punto 2:
    nel file mostra_utenti.php cerchi tra i parametri POST uno con il nome "params". In realtà, dal codice JS invio un parametro con nome "q".

    quindi devi sostituire la riga
    codice:
    $q=$_POST['params'];
    con
    codice:
    $q=$_POST['q'];
    Punto 3:
    il controllo
    codice:
    if ($sql!==false) {echo "non va la query";}
    non ha senso

    Punto 4:
    devi aggiungere nel codice JS l'istruzione che inserirà l'HTML, di ritorno dal file mostra_utenti.php, nel div "info" che è presente in fondo al file.

    Se hai altre richieste non esitare a chiedere

    Saluti.

  3. #3
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    144
    Ciao, grazie mille per l'aiuto, ma ho ancora qualche dubbio... innanzitutto tu mi ha scritto:

    "nel codice che hai modificato non viene creato un file XML come risultato di una query ma quello che viene restituito è plain text."

    Come faccio a creare il file xml dalla query?

    Ti posto qui il codice nuovo:

    Codice PHP:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Post</title>
    </head>
    <body>
    <div id="xmldata"></div>
    <script type="text/javascript"> 

    function readyAJAX() { 
    try { 
        return new XMLHttpRequest(); 
    } catch(e) { 
        try { 
            return new ActiveXObject('Msxml2.XMLHTTP'); 
        } catch(e) { 
            try { 
                return new ActiveXObject('Microsoft.XMLHTTP'); 
            } catch(e) { 
                return "Hai bisogno di un altro browser."; 
            } 
        } 



    function mostraInfo(data)
    {
    var requestObj = readyAJAX(); 
    var url = "mostra_utenti.php"; 
    var params = "q=" + data;
    requestObj.open("POST",url,true); 
    requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    requestObj.send(params); 
    requestObj.onreadystatechange = function() { 
        if (requestObj.readyState == 4) {   
            if (requestObj.status == 200) { 
                alert(requestObj.responseText); 
            } else { 
                alert(requestObj.statusText); 
            } 
        } 

    }
    </script> 
    <form>
    Seleziona Dipendente:
    <select name="users" onChange="mostraInfo(this.value)">
    <?php

    $db_host 
    "localhost";
    $db_user "administrator";
    $db_password "administrator";
    $db_database "ticket";

    //Seleziono quelli che sono i dipendenti
    $connessione mysql_connect($db_host,$db_user,$db_password);
    mysql_select_db($db_database$connessione);

    $query "SELECT * FROM user ";
    $result mysql_query($query);
    while(
    $riga mysql_fetch_array($result)){
    echo 
    "<option value='$riga[user_id]'>$riga[user_firstname] $riga[user_lastname]</option>";
    }

    ?>
    </select>
    </form>


    <div id="info"></div>
    </body>
    </html>

    e l'altro file è

    Codice PHP:

    <?php
    $db_host 
    "localhost";
    $db_user "administrator";
    $db_password "administrator";
    $db_database "ticket";


    $q=$_POST['q'];

    $con mysql_connect($db_host,$db_user,$db_password);
    mysql_select_db($db_database$con);



    $sql="SELECT *
    FROM user 
    WHERE user_id = '"
    .$q."'";

    $result mysql_query($sql);
     

    echo 
    "<table border='1'>
    <tr>
    <th>Nome</th>
    <th>Cognome</th>
    <th>Username</th>
    <th>Password</th>
    <th>Email</th>
    </tr>"
    ;

    while(
    $row mysql_fetch_array($result))
    {
    echo 
    "<tr>";
    echo 
    "<td>" $row['user_firstname'] . "</td>";
    echo 
    "<td>" $row['user_lastname'] . "</td>";
    echo 
    "<td>" $row['user_username'] . "</td>";
    echo 
    "<td>" $row['user_password'] . "</td>";
    echo 
    "<td>" $row['user_email'] . "</td>";
    echo 
    "</tr>";
    }
    echo 
    "</table>";

    mysql_close($con);
    ?>

    Ma non funziona comunque...
    Tu mi hai detto che:

    "devi aggiungere nel codice JS l'istruzione che inserirà l'HTML, di ritorno dal file mostra_utenti.php, nel div "info" che è presente in fondo al file."

    come faccio?


    Con questo codice sopra se provo con firefox o IE8 quando seleziono il nome mi viene una finestra di alert, esattamente quella che nel codice è questa:
    codice:
    alert(requestObj.responseText);
    con dentro scritto:
    lo user_id corretto in base a che nome scelgo, seguito da questo codice:
    codice:
    "<table border='1'><tr>  <th>Nome</th>  <th>Cognome</th>  <th>Username</th>  <th>Password</th>  <th>Email</th>  </tr>";
    e poi tra vari tr e td i giusti campi user_firstname, user_lastname ecc...

    Quindi accede al database e li prende correttamente, funziona anche correttamente, ma stampando il tutto su una finsestra di alert, ovviamente non vede la tabella che ho fatto con php dentro all'echo del secondo file.... Consigli?



    Scusa per il disturbo, ti ringrazio in anticipo
    Saluti
    Andrea

  4. #4
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    144
    Ok come non detto, ho aggiunto questa riga nel primo file qui:

    codice:
    if (requestObj.readyState == 4) 
    {  
    if (requestObj.status == 200) 
    {   
        var a=(requestObj.responseText);    
        document.getElementById('info').innerHTML = a;          
    } 
    else 
    {       
        alert(requestObj.statusText);          
    }

    e funziona tutto correttamente...
    Una domanda, con quello che ho scritto ho fatto quello che intendevo realmente ottenere?
    Cioè codificare i dati in xml e passarli con una chiamata ajax?

    Grazie milla
    Ciao
    Andrea

  5. #5
    Hai utilizzato AJAX, ma non hai creato un file XML.
    Che comunque non è obbligatorio.
    Il file XML deve essere creato dallo script php, ma comporta una modifica non indifferente anche del codice JS e per una cosa semplice come la tua non so se ne vale la pena.
    Se hai effettivamente bisogno di generare un XML, io sono qua

    Saluti.

  6. #6
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    144
    Si, grazie mille per la disponibilità. Siccome vorrei adattare il codice anche per cose più sicure in avanti, come pagamenti o cose simili, mi potresti indicare come devo modificare il codice per codificare in xml?
    Grazie mille, sempre molto gentili

  7. #7
    Il file php dovrà inziare con

    Codice PHP:
       header('Content-Type: text/xml'); 
    indicando che l'output prodotto sarà XML.

    Seguirà poi, dopo la connessione al db e l'esecuzione della query, la costruzione del documento vero e proprio:

    Codice PHP:
        $xml = new DomDocument('1.0');
        
    $info $xml->createElement('informations');
        
    $info $xml->appendChild($info);

        while (
    $row mysql_fetch_array($result)) 
        {
            
    $firstname $xml->createElement('firstname');
            
    $firstname $info->appendChild($firstname);
            
    $value $xml->createTextNode($row['user_firstname']);
            
    $value $firstname->appendChild($value);
                
            
    $lastname $xml->createElement('lastname');
            
    $lastname $info->appendChild($lastname);
            
    $value $xml->createTextNode($row['user_las    tname']);
            
    $value $lastname->appendChild($value);    

            
    $username $xml->createElement('username');
            
    $username $info->appendChild($username);
            
    $value $xml->createTextNode($row['user_username']);
            
    $value $username->appendChild($value);

            
    $password $xml->createElement('password');
            
    $password $info->appendChild($password);
            
    $value $xml->createTextNode($row['user_password']);
            
    $value $password->appendChild($value);

            
    $email $xml->createElement('email');
            
    $email $info->appendChild($email);
            
    $value $xml->createTextNode($row['user_email']);
            
    $value $email->appendChild($value);
        }
            
    $output $xml->saveXML(); 

    e questo produrrà un output del tipo

    codice:
    <informations>
    	<user>
    		<firstname>
    			Paolo
    		</firstname>
    		<lastname>
    			Rossi
    		</lastname>
    		<username>
    			paolo.rossi
    		</username>
    		<password>
    			miapassword
    		</password>
    		<email>
    			paolo.rossi@mail.com
    		</email>
    	</user>
    </informations>
    mentre nello script JS, dove adesso stampi la risposta del server nel tag div, dovrai inserire questo codice

    codice:
       var serverResponse = requestObj.responseXML;
       var header = serverResponse.getElementsByTagName("user");
    
       htmlString = "<table><tr><th>Nome</th><th>Cognome</th><th>Username</th><th>Password</th><th>Email</th></tr>";
    		
       for (i=0; i<header.length; i++)
       {
          htmlString += "<tr>";
          if (window.ActiveXObject)
          {
             htmlString += "<td>" + header[i].childNodes[0].text + "</td>";
             htmlString += "<td>" + header[i].childNodes[1].text + "</td>";
             htmlString += "<td>" + header[i].childNodes[2].text + "</td>";
             htmlString += "<td>" + header[i].childNodes[3].text + "</td>";
             htmlString += "<td>" + header[i].childNodes[4].text + "</td>";
          }
          else
          {
             htmlString += "<td>" + header[i].childNodes[0].textContent + "</td>";
             htmlString += "<td>" + header[i].childNodes[1].textContent + "</td>";
             htmlString += "<td>" + header[i].childNodes[2].textContent + "</td>";
             htmlString += "<td>" + header[i].childNodes[3].textContent + "</td>";
             htmlString += "<td>" + header[i].childNodes[4].textContent + "</td>";
          }
          htmlString += "</tr>";
       }
       htmlString += "</table>";
    
       document.getElementById('info').innerHTML = htmlString;
    ti avverto che il codice non ho avuto tempo di provarlo.

  8. #8
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    144
    Grazie mille, adesso lo provo subito!

    Scusa non è che potresti guardare qua che ho un altro problema? Sei un santo


    http://forum.html.it/forum/showthrea...readid=1403517

  9. #9
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    144
    Scusa non ho ben capito dove devo mettere le cose

    io ho scritto questo ma è sbagliato, saresti così gentile da postarmi la cosa corretta così cerco di capire bene come funziona? Grazie mille

    codice:
    <?php
    header('Content-Type: text/xml');
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Post</title>
    </head>
    <body>
    <div id="xmldata"></div>
    <script type="text/javascript"> 
    
    function readyAJAX() { 
    try { 
        return new XMLHttpRequest(); 
    } catch(e) { 
        try { 
            return new ActiveXObject('Msxml2.XMLHTTP'); 
        } catch(e) { 
            try { 
                return new ActiveXObject('Microsoft.XMLHTTP'); 
            } catch(e) { 
                return "Hai bisogno di un altro browser."; 
            } 
        } 
    } 
    } 
    
    function mostraInfo(data)
    {
    var requestObj = readyAJAX(); 
    var url = "mostra_utenti.php"; 
    var params = "q=" + data;
    requestObj.open("POST",url,true); 
    requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    requestObj.send(params); 
    
    
    var serverResponse = requestObj.responseXML;
       var header = serverResponse.getElementsByTagName("user");
    
       htmlString = "<table><tr><th>Nome</th><th>Cognome</th><th>Username</th><th>Password</th><th>Email</th></tr>";
    		
       for (i=0; i<header.length; i++)
       {
          htmlString += "<tr>";
          if (window.ActiveXObject)
          {
             htmlString += "<td>" + header[i].childNodes[0].text + "</td>";
             htmlString += "<td>" + header[i].childNodes[1].text + "</td>";
             htmlString += "<td>" + header[i].childNodes[2].text + "</td>";
             htmlString += "<td>" + header[i].childNodes[3].text + "</td>";
             htmlString += "<td>" + header[i].childNodes[4].text + "</td>";
          }
          else
          {
             htmlString += "<td>" + header[i].childNodes[0].textContent + "</td>";
             htmlString += "<td>" + header[i].childNodes[1].textContent + "</td>";
             htmlString += "<td>" + header[i].childNodes[2].textContent + "</td>";
             htmlString += "<td>" + header[i].childNodes[3].textContent + "</td>";
             htmlString += "<td>" + header[i].childNodes[4].textContent + "</td>";
          }
          htmlString += "</tr>";
       }
       htmlString += "</table>";
    
       document.getElementById('info').innerHTML = htmlString;    
    
    
    }
    </script> 
    <form>
    Seleziona Dipendente:
    <select name="posti" onChange="mostraInfo(this.value)">
    <?php
    
    
    
             
    
    
    $db_host = "localhost";
    $db_user = "administrator";
    $db_password = "administrator";
    $db_database = "ticket";
    
    //Seleziono quelli che sono i dipendenti
    $connessione = mysql_connect($db_host,$db_user,$db_password);
    mysql_select_db($db_database, $connessione);
    
    $query = "SELECT * 
    FROM teatro 
    WHERE disp='true'";
    $result = mysql_query($query);
    while($riga = mysql_fetch_array($result)){
    echo "<option value='$riga[id]'>fila $riga[fila] posto$riga[posto]</option>";
    
    
    $xml = new DomDocument('1.0'); 
        $info = $xml->createElement('informations'); 
        $info = $xml->appendChild($info); 
    
        while ($row = mysql_fetch_array($result)) 
        { 
            $firstname = $xml->createElement('firstname'); 
            $firstname = $info->appendChild($firstname); 
            $value = $xml->createTextNode($row['user_firstname']); 
            $value = $firstname->appendChild($value); 
                 
            $lastname = $xml->createElement('lastname'); 
            $lastname = $info->appendChild($lastname); 
            $value = $xml->createTextNode($row['user_las    tname']); 
            $value = $lastname->appendChild($value);     
    
            $username = $xml->createElement('username'); 
            $username = $info->appendChild($username); 
            $value = $xml->createTextNode($row['user_username']); 
            $value = $username->appendChild($value); 
    
            $password = $xml->createElement('password'); 
            $password = $info->appendChild($password); 
            $value = $xml->createTextNode($row['user_password']); 
            $value = $password->appendChild($value); 
    
            $email = $xml->createElement('email'); 
            $email = $info->appendChild($email); 
            $value = $xml->createTextNode($row['user_email']); 
            $value = $email->appendChild($value); 
        } 
    
    $output = $xml->saveXML();
    }
    
    ?>
    </select>
    </form>
    
    
    <div id="info"></div>
    </body>
    </html>

  10. #10
    Hai mischiato un po' di cose

    Qual è l'output che vuoi ottenere?
    Ho visto che hai aggiunto una query per i posti ma non capisco il nesso.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.