Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 12
  1. #1

    problema ajax post form (non invia i dati post)

    Ciao a tutti, stavo provando un semplice script per inviare, tramite metodo ajax-php, dei dati POST da una textarea al database. Il problema non è tanto il collegamento al db ma la scrittura del dato post nel database, è l'unico dato che non mi salva.

    Posto il codice, questo è l'html
    codice:
    <html>
    <head>
    <script type="text/javascript" src="textarea.js"></script>
    </head>
    <body>
    <form method="post" action="invia.php" name="MyForm">
    <textarea cols="30" rows="4" name="message_text"></textarea>
    invia
    </form>
    </body>
    </html>
    questo è il js

    codice:
    function createXmlHttpRequestObject() 
    {
      var xmlHttp;
    
      try
      {
        xmlHttp = new XMLHttpRequest();
      }
      catch(e)
      {
        
        var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                        "MSXML2.XMLHTTP.5.0",
                                        "MSXML2.XMLHTTP.4.0",
                                        "MSXML2.XMLHTTP.3.0",
                                        "MSXML2.XMLHTTP",
                                        "Microsoft.XMLHTTP");
       
        for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
        {
          try 
          { 
            
            xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
          } 
          catch (e) {} 
        }
      }
     
      if (!xmlHttp)
    	  alert("Error creating the XMLHttpRequest object.");
      else 
     
        return xmlHttp;
    }
    
    
    function process()
    {
     
      if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
      {
       
        	params = document.getElementsByTagName("message_text").value;
    
            xmlHttp.open("POST", "invia.php", true);
            xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlHttp.onreadystatechange = handleServerResponse;
            xmlHttp.send(params);
      }
      else
        
        setTimeout('process()', 1000);
    }
    
    
    function handleServerResponse() 
    {
      
      if (xmlHttp.readyState == 4) 
      {
        
        if (xmlHttp.status == 200) 
        {
    	//DO NOTHING
        } 
       
        else 
        {
          alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
      }
    }
    questo è il php

    codice:
    <?php
    
    require("db_config.php");
    $message = pg_escape_string($_POST["message_text"]);
    
    $dayOfWeek = date("l - d-m-Y - H:i:s");
    
    
    $query = "INSERT INTO messages (content, created)
    		VALUES ('" . $message . "', '" . $dayOfWeek . "')";
    pg_query($query);
    
    ?>
    provando mi scrive correttamente il valore $dayOfWeek alla click sul link "invia", segno che il collegamento c'è, il problema sembra proprio come passare il dato POST, poichè sul db mi ritorna un valore nullo. Qualcuno ha qualche idea?

    Grazie in anticipo
    Perpetual Ribellion With Absolutely No Cause

  2. #2
    Moderatore di JavaScript L'avatar di br1
    Registrato dal
    Jul 1999
    Messaggi
    19,998
    E questa dove l'hai vista?

    params = document.getElementsByTagName("message_text").valu e;

    Il metodo si riferisce al nome generico del tag (div, table, a, eccetera) e non all'attributo name dello stesso....

    Assegnagli un id e usa il metodo getElementById()

    ciao
    Il guaio per i poveri computers e' che sono gli uomini a comandarli.

    Attenzione ai titoli delle discussioni: (ri)leggete il regolamento
    Consultate la discussione in rilievo: script / discussioni utili
    Usate la funzione di Ricerca del Forum

  3. #3
    ho provato sia con l'id sia con il tag name, nulla da fare..
    Perpetual Ribellion With Absolutely No Cause

  4. #4
    Moderatore di JavaScript L'avatar di br1
    Registrato dal
    Jul 1999
    Messaggi
    19,998
    Se non richiami la funzione createXmlHttpRequestObject() l'oggetto che ti serve non viene creato....

    Non e' che ti convenga ripartire da zero e seguire l'esempio che hai utilizzato dall'inizio?
    Il guaio per i poveri computers e' che sono gli uomini a comandarli.

    Attenzione ai titoli delle discussioni: (ri)leggete il regolamento
    Consultate la discussione in rilievo: script / discussioni utili
    Usate la funzione di Ricerca del Forum

  5. #5
    In effetti ero rimasto un po' perrplesso del fatto che non venisse richiamata da nessuna parte, ma visto che sto studiando l'esempio e vedendo che il php è stato comunque richiamato asincronamente non mi ci ero soffermato, di preciso dove dovrei richiamare la funzione? Grazie per il supporto.
    Perpetual Ribellion With Absolutely No Cause

  6. #6
    con un onLoad() sul body tag?
    Perpetual Ribellion With Absolutely No Cause

  7. #7
    Moderatore di Annunci siti web, Offro lavoro/collaborazione, Cerco lavoro L'avatar di cavicchiandrea
    Registrato dal
    Aug 2001
    Messaggi
    26,133
    Cavicchi Andrea
    Problemi con javascript, jquery, ajax clicca qui

  8. #8
    ho fatto ulteriori test ma la situazione non è cambiata, inoltre ho consultato l'error.log di apache per capire bene cosa accade quando il file invia.php viene richiamato, ed infatti mi ritorna un errore:

    PHP Notice: Undefined index: messagetext in C:\\Inetpub\\wwwroot\\php\\message\\invia.php on line 11, referer: http://localhost/message/testtextarea.php

    non capisco perchè non trovi il riferimento a messagetext.. per completezza riposto i files leggermente modificati per le prove.

    l'id è indicato nel file testtextarea.php con
    <textarea cols="30" rows="4" id="messagetext"></textarea>


    mentre il valore viene recuperato in textarea.js con
    var params = document.getElementById("messagetext").value;

    nell'invia.php invece ho
    $message = $_POST["messagetext"];


    testtextarea.php :
    codice:
    <?php
    session_start();
    ?>
    <html>
    <head>
    <script type="text/javascript" src="textarea.js"></script>
    </head>
    <body>
    
    <textarea cols="30" rows="4" id="messagetext"></textarea>
    invia
    
    </body>
    </html>
    textarea.js :
    codice:
    // holds an instance of XMLHttpRequest
    var xmlHttp = createXmlHttpRequestObject();
    
    // creates an XMLHttpRequest instance
    function createXmlHttpRequestObject() 
    {
      // will store the reference to the XMLHttpRequest object
      var xmlHttp;
      // this should work for all browsers except IE6 and older
      try
      {
        // try to create XMLHttpRequest object
        xmlHttp = new XMLHttpRequest();
      }
      catch(e)
      {
        // assume IE6 or older
        var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                        "MSXML2.XMLHTTP.5.0",
                                        "MSXML2.XMLHTTP.4.0",
                                        "MSXML2.XMLHTTP.3.0",
                                        "MSXML2.XMLHTTP",
                                        "Microsoft.XMLHTTP");
        // try every prog id until one works
        for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
        {
          try 
          { 
            // try to create XMLHttpRequest object
            xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
          } 
          catch (e) {} // ignore potential error
        }
      }
      // return the created object or display an error message
      if (!xmlHttp)
    	  alert("Error creating the XMLHttpRequest object.");
      else 
     
        return xmlHttp;
    }
    
    // make asynchronous HTTP request using the XMLHttpRequest object 
    function process()
    {
      // proceed only if the xmlHttp object isn't busy
      if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
      {
        // retrieve the name typed by the user on the form
        	var params = document.getElementById("messagetext").value;
    	
    
            xmlHttp.open("POST", "http://localhost/message/invia.php", true);
            xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlHttp.onreadystatechange = handleServerResponse;
            xmlHttp.send(params);
      }
      else
        // if the connection is busy, try again after one second  
        setTimeout('process()', 1000);
    }
    
    // executed automatically when a message is received from the server
    function handleServerResponse() 
    {
      // move forward only if the transaction has completed
      if (xmlHttp.readyState == 4) 
      {
        // status of 200 indicates the transaction completed successfully
        if (xmlHttp.status == 200) 
        {
    	//DO NOTHING
        } 
        // a HTTP status different than 200 signals an error
        else 
        {
          alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
      }
    }
    invia.php :
    codice:
    <?php
    session_start();
    
    require("db_config.php");
    
    header('Expires: Wed, 23 Dec 1980 00:30:00 GMT');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: no-cache, must-revalidate');
    header('Pragma: no-cache');
    
    $message = $_POST["messagetext"];
    
    $dayOfWeek = date("l - d-m-Y - H:i:s");
    
    
    $query = "INSERT INTO messages (post_id, user_id, content, created)
    		VALUES ('23', '1', '" . $message . "', '" . $dayOfWeek . "')";
    pg_query($query);
    
    ?>
    Perpetual Ribellion With Absolutely No Cause

  9. #9
    Utente di HTML.it
    Registrato dal
    Dec 2010
    Messaggi
    3,660
    prova cosi:

    var params = "messagetext="+document.getElementById("messagetex t").value;

  10. #10
    con questa modifica funziona! Grazie mille, era un po' che ci sbattevo la testa! Comunque strano in vari esempi non ho trovato questa specifica di scrivere per esteso il nome dell'id di riferimento
    Perpetual Ribellion With Absolutely No Cause

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.