Mysql
 sql >> Database >  >> RDS >> Mysql

Invia il modulo ajax e rimani sulla stessa pagina non funzionante

Il modulo viene inviato e non rimane sulla stessa pagina a causa dell'attributo action sul modulo e del normale pulsante di invio.

Che porta al tuo .submit() metodo incluso .preventDefault() probabilmente non viene interpretato neanche dopo il caricamento dell'html.

Potresti fare qualcosa sulla falsariga di questo:

<html>
  ...
  <body>
  ...
    <form id="formA" action="test.php" method="post" enctype="multipart/form-data">
      <input id="commentData" name="commentData" type="text" />
      <input type="submit" value="toDb" id="toDB" name="toDB" />
    </form>
  ...
  </body>
  <script>
   ...script here...
  </script>
 </html>

E il javascript potrebbe essere qualcosa sulla falsariga di:

( function( $ )
  {
    var submit = $( 'input[id=toDB]' );
    $( submit ).on
    (
      'click',
      function( event )
      {
        event.preventDefault();
        var form = $( this ).parent();

        // Get form fields
        var data = $( form ).serializeArray(), obj = {}, j = 0;
        for( var i = 0; i < data.length; i++ )
        {
          if( data[i].name in obj )                                                                  
          {
            var key = data[i].name + '_' + j;
            obj[key] = data[i].value;
            j++;
          }
          else
          {
            obj[data[i].name] = data[i].value;
          }
        };

        // Make AJAX request
        $.ajax
        (
          {   
            url: $( form ).attr( 'action' ),    
            type: 'POST',
            data: 'toDB=' + JSON.stringify( obj ),    
            success: function( data, textStatus, xhr )
            {
              // Do something with data?
              ...    
              alert( 'ok' );    
            }
          }
        );
      }
    );
  }( jQuery )
);

Vedi il jsfiddle per te stesso.

Puoi dire che funziona perché ricevi un errore della console che indica che la destinazione della richiesta non è stata trovata - 404 - anche se la pagina non si aggiorna, rimani esattamente dove sei... con una pagina adeguata da inviare ad essa funziona completamente.

MODIFICA

Ho modificato l'impostazione di 'data' in ajax() call in modo che i campi del modulo siano impostati come una stringa json su una variabile POST [toDB].

Quindi nel tuo PHP faresti:

$datas = json_decode( $_POST['toDB'], true );

E ora i tuoi $datas variabile è un array associativo contenente tutti i nomi e i valori dei campi del modulo. Non sono al 100% su questa prossima affermazione, ma potrebbe essere necessario utilizzare stripslashes() di PHP metodo sui dati POSTED prima di utilizzare json_decode()

cioè:

//Connect to database server
mysql_connect( "localhost", "user", "" ) or die ( mysql_error() );
mysql_select_db( "test" ) or die( mysql_error() );
$strSQL = "SELECT * FROM comments order by RAND() LIMIT 5";
$rs = mysql_query( $strSQL );

if( !$rs ) 
{
  echo 'Could not run query ' . mysql_error();
  exit;
}

$dt1=date("Y-m-d");

if( isset( $_POST['toDB'] ) )
{
  $datas = json_decode( stripslashes( $_POST['toDB'] ), true );
  $dataA = $datas['commentData'];
  $sql = "INSERT INTO comments( id, comment, datum )VALUES( DEFAULT, '" . $dataA . "', '" . $dt1 . "' );";
  $result=mysql_query( $sql );
}
mysql_close();

Spero di esserti stato d'aiuto