Visualizzazione dei risultati da 1 a 7 su 7
  1. #1
    Utente di HTML.it
    Registrato dal
    Sep 2005
    Messaggi
    361

    [Ajax] Problemi con un form

    Sto cercando di fare l'inserimento di un campo nel db con ajax..però non mi funziona..vi posto il codice..

    ajax.js
    codice:
    function assegnaXMLHttpRequest() {
    	var
    		XHR = null,
    		browserUtente = navigator.userAgent.toUpperCase();
    
    	if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object")
    		XHR = new XMLHttpRequest();
    		else if(window.ActiveXObject && browserUtente.indexOf("MSIE 4") < 0) {
    			if(browserUtente.indexOf("MSIE 5") < 0)
    				XHR = new ActiveXObject("Msxml2.XMLHTTP");
    			else
    				XHR = new ActiveXObject("Microsoft.XMLHTTP");
    		}
    		return XHR;
    };
    
    // funzione per prendere un elemento con id univoco
    function prendiElementoDaId(id_elemento) {
    	var elemento;
    		if(document.getElementById)
    			elemento = document.getElementById(id_elemento);
    		else
    			elemento = document.all[id_elemento];
    		return elemento;
    };
    
    function inserisci_marca(){
    	var parametri = "nome=" + escape(document.forms['ins_marca'].nome.value);
    		ajax = assegnaXMLHttpRequest(); //Creo l'oggetto xmlhttp
    		elemento = prendiElementoDaId('msg'); //Div nel quale inserirò la lista
    	if(ajax){
    		
    			ajax.open("POST", 'ins_marca.php', true);
       			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    	        ajax.setRequestHeader('Content-length',parametri.length);
    	        ajax.setRequestHeader('Connection', 'close');
    
    			if(ajax.readyState === readyState.COMPLETATO) {
    				// verifica della risposta da parte del server
    				if(statusText[ajax.status] === "OK")
    				  // operazione avvenuta con successo
    				  
    				  elemento.innerHTML = ajax.responseText;
    				else {
    					// errore di caricamento
    					elemento.innerHTML = "Impossibile effettuare l'operazione richiesta.
    ";
    					elemento.innerHTML += "Errore riscontrato: " + statusText[ajax.status];
    				}
    			} 
    		ajax.send(parametri);
    	}
    	return false;
    }
    Questo è il form:
    codice:
    		<form id="ins_marca">
    			<table border="0" cellspacing="0" cellpadding="0" width="300">
    				<tr>
    					<td width="300">Nome Marca</td>
    				</tr>
    				<tr>
    					<td width="300"><input type="text"  name="nome" size="25" style="width: 170; border: 1px solid #afb4b8; font-size:10px; font-family: Tahoma,Arial,sans-serif; color: black; font-weight: normal; margin-bottom:5px;" /></td>
    				</tr>	
    				<tr>
    					<td width="300">
    					<input type="button" name="invia" value="inserisci" onClick="javascript:inserisci_marca(); return false;" />
    					</td>
    				</tr>
    			</table>
    		</form>
    		<div id="messaggino">
    		
    		</div>
    il div id=messaggio conterrà il messaggio di buon fine..

    per prova la pagina ins_marca.php ha solo la stampa del parametro passato tramite post
    Codice PHP:
    <?
    echo($_POST['nome']);
    ?>
    non c'è un errore vero e proprio.. il div non viene aggiornato...
    credo non entri in questo if
    if(statusText[ajax.status] === "OK")
    // operazione avvenuta con successo

    elemento.innerHTML = ajax.responseText;
    else {
    help please

  2. #2
    Utente di HTML.it
    Registrato dal
    Sep 2005
    Messaggi
    361
    ho provato anche a fare tramite GET...
    ma non va...

    codice:
    function inserisci_marca(){
    var
    		ajax = assegnaXMLHttpRequest(); //Creo l'oggetto xmlhttp
    		elemento = prendiElementoDaId('msg'); //Div nel quale inserirò la lista
    	if(ajax){
    		
    			ajax.open("get", "ins_marca.php?nome=" + escape(document.forms['ins_marca'].nome.value), true);
    	        ajax.setRequestHeader('Connection', 'close');
    			
    			if(ajax.readyState === readyState.COMPLETATO) {
    				
    				// verifica della risposta da parte del server
    				if(statusText[ajax.status] === "OK")
    				  // operazione avvenuta con successo
    				  
    				  elemento.innerHTML = ajax.responseText;
    				else {
    					// errore di caricamento
    					elemento.innerHTML = "Impossibile effettuare l'operazione richiesta.
    ";
    					elemento.innerHTML += "Errore riscontrato: " + statusText[ajax.status];
    				}
    			} else {
    				alert(ajax.readyState);	
    			}
    		ajax.send(null);
    	}
    	return true;
    }

  3. #3
    Utente di HTML.it
    Registrato dal
    Sep 2005
    Messaggi
    361
    il readyState è sempre fisso a 1 perché?

  4. #4
    Utente di HTML.it L'avatar di pietro09
    Registrato dal
    Jan 2002
    Messaggi
    10,116
    ti do un esempio: prendi il codice javascript, non quello server
    codice:
    <%@ Page Language="C#" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
        protected void Page_Load(object sender, EventArgs e)
        {
            string comando_ajax = ModuloWeb.RequestParams("comando_ajax");
            if (comando_ajax == "aggiorna_database") aggiorna_database();
        }
    
        void aggiorna_database()
        {
            string testo = "";
            string sql = "UPDATE CAMPI SET TESTO = ? WHERE ID = 1 ";
            OleDbConnection con = null;
            try
            {
                testo = ModuloWeb.RequestParams("testo");
                con = new OleDbConnection(MioModulo.StringaConnessioneTest);
                con.Open();
                OleDbCommand com = con.CreateCommand();
                com.CommandText = sql;
                com.Parameters.Add("testo", OleDbType.VarChar, 50).Value = ModuloWeb.StringNullToDBNull(testo);
                com.ExecuteNonQuery();
                this.Response.Write("Tabella aggiornata con successo");
            }
            catch
            {
                this.Response.Write("Errore aggiornamento tabella");
            }
            finally
            {
                if (con != null) con.Close();
            }
            Response.End();   
        }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Pagina senza titolo</title>
        <link href="../../../stili/Styles.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="../../../js/sajax.js"></script>
    
        <script language="javascript" type="text/javascript">
    // <!CDATA[
    
    function Button1_onclick() 
    {
        var parametri = "testo=" + $("Text1").value;
        sajax("?comando_ajax=aggiorna_database", onload, parametri);
        function onload()
        {
            $("div1").innerHTML = this.request.responseText;
        }
    
    }
    
    // ]]>
        </script>
    </head>
    <body>
        <form id="form1" runat="server" >
            <label for="Text1">nome: </label>
            <input id="Text1" type="text" style="border:1px black solid;" />
            <input id="Button1" type="button" value="aggiorna" onclick="Button1_onclick();"/>
            <div id="div1"></div>
        </form>
    </body>
    </html>

    la funzione ajax è
    codice:
    // File JScript
    function sajax(url, onload, parameters, onerror)
    {
    	parameters = (parameters == undefined)? "" : parameters;
    	
    	//creazione oggetto per richiesta web
    	var objHTTP = getXMLHttp();
    	objHTTP.open("post", url, true);
    	objHTTP.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    	objHTTP.setRequestHeader('Content-length',parameters.length);
    	objHTTP.setRequestHeader('Connection', 'close');
    
    	objHTTP.onreadystatechange = function() 
    	{ 
    		if (objHTTP.readyState == 4) 
    		{
    			if (objHTTP.status == 200 || objHTTP.status == 0)
    			{
    				this.request = objHTTP;
    				if(onload) onload.call(this);
    			}											
    			else {if(onerror && typeof(onerror) == "function") {onerror(defaultError); return;}else {defaultError(); return;}}
    		}
    	};
    
        objHTTP.send(parameters);
        
    
        function getXMLHttp() 
        {
    	    var xmlhttp = null;
        	
    	    if(window.XMLHttpRequest) 
    	    {
    		    xmlhttp = new XMLHttpRequest(); // Gecko (Firefox, Moz), KHTML (Konqueror, Safari), Opera, Internet Explorer 7
    	    } 
    	    else if(window.ActiveXObject) 
    	    {
    		    try
    		    {
    			    xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); // Internet Explorer 6 
    		    } 
    		    catch(e) 
    		    {
    			    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer 4,5 
    		    }
    		    } 
    	    else 
    	    {
    		    xmlhttp = null;
    	    }
    	    return xmlhttp;
        };
    
    	function defaultError()
    	{
    		alert("ERRORE NELLA TRASMISSIONE DATI!");
    	};
    }
    
    //al posto di mettere document.getElementById("div1"), mettere $("div1")
    //da prototype.js
    function $() {
      var elements = new Array();
    
      for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
          element = document.getElementById(element);
    
        if (arguments.length == 1)
          return element;
    
        elements.push(element);
      }
    
      return elements;
    }
    Pietro

  5. #5
    Utente di HTML.it
    Registrato dal
    Sep 2005
    Messaggi
    361
    grazie mille..
    però ho provato a riscriverla da capo... mettendo nomi diversi e funziona :S

    non so cosa cambi tra questa e la precedente
    codice:
    function add_brand(){
    	var 
    		http = assegnaXMLHttpRequest();
    		elemento = prendiElementoDaId('messaggino');
    	if(http){
    		//alert("ins_marca.php?nome" + escape(document.forms['ins_marca'].nome.value));
    		http.open("get","ins_marca.php?nome=" + escape(document.forms['ins_marca'].nome.value),true);
    		http.setRequestHeader("connection", "close");
    		http.onreadystatechange = function() {
    						  
    						  // verifica dello stato
    						  if(http.readyState === readyState.COMPLETATO) {
    							  
    							// verifica della risposta da parte del server
    							if(statusText[http.status] === "OK")
    							  // operazione avvenuta con successo
    							  
    							  elemento.innerHTML = http.responseText;
    							else {
    							  // errore di caricamento
    							  elemento.innerHTML = "Impossibile effettuare l'operazione richiesta.
    ";
    							  elemento.innerHTML += "Errore riscontrato: " + statusText[http.status];
    							}
    						  } 
    						}
    			    // invio richiesta
    						http.send(null);
    	}
    	return true;
    }

  6. #6
    Utente di HTML.it L'avatar di pietro09
    Registrato dal
    Jan 2002
    Messaggi
    10,116
    sono felice che ti funzioni ma credo che il problema generale in queste questioni, sia quello di farsi una funzione generale di libreria riutilizzabile
    Pietro

  7. #7
    Utente di HTML.it
    Registrato dal
    Sep 2005
    Messaggi
    361
    io non ho capito una cosa..ma ogni volta che modifico il file .js che contiene le funzioni devo riavviare il browser?
    sennò mi da i risultati della versione non salvata...

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.