Submit the ajax form and stay on the same page not working

I want to store user comments in my database. When the user submits, I don't want to redirect them to a new page. I have the following code, but it doesn't work.

My HTML code:

<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>

      

JavaScript:

var frm = $('#formA');

$(document).submit(function(e) {
e.preventDefault();

$.ajax({

    url: frm.attr('action'),

    type: frm.attr('method'),

    data: frm.serialize(),

    success: function(html) {

        alert('ok');

    }

});
});

      

Here is my PHP file:

//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'])){
  $dataA = $_POST['commentData'];
  $sql = "INSERT INTO comments(id, comment, datum)VALUES(DEFAULT,'$dataA', '$dt1')";
  $result=mysql_query($sql);
}
mysql_close();

      

When I click the submit button, it will stay on the same page and show a warning, but the input field data will not be inserted into my database. When I remove e.preventDefault (), the data goes into the database, but the page is redirected to test.php

Tried different things but couldn't figure it out. Can anyone help me? Thanks in advance!

+3


source to share


3 answers


The form submits and does not stay on the same page due to the action attribute on the form and the normal submit button.

Which results in your method .submit()

including .preventDefault()

probably not being interpreted after the html is loaded.

You can do something like this:

<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>

      

And the javascript can be something like:

( 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 )
);

      

See the jsfiddle for yourself.

You can tell it works because you get a console error that the destination address was not found - 404 - although the page is not refreshed, you are right where you are ... with the appropriate page to submit the entire job to it.



EDIT

I changed the "data" setting in the call ajax()

so that the form fields are set as json string to the POST variable [toDB].

So, in your PHP, you would do:

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

      

And now your variable $datas

is an associative array containing all the names and values โ€‹โ€‹of the form fields. I am not 100% in this next statement, but you may need to use the PHP method stripslashes()

on the POSTED data before usingjson_decode()

i.e:.

//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();

      

Hope it helps

+2


source


Do it through the form submit event

var frm = $('#formA');
frm.submit(function(e) {
  //....
  //....
  e.preventDefault();
});

      

And yes, sanitize DB inserts with mysql_real_escape_string($dataA)

to prevent SQL injection.

EDIT sorry, incomplete answer (you still need to use submit on form and not on document)

EDIT2 :) incorrect use of $ (this) :)

$('#formA').submit(function(e) {  
  var formAction = $(this).attr('action');
  var formData = $(this).serialize();
  $.ajax({   
    url: formAction,    
    type: 'POST',     // try uppercase, 'post' !== 'POST', dont know if this must be uppercase or can be lowercase
    data: formData, // or try  $(this).serializeArray()    
    success: function(html) {    
        alert('ok');    
    })
  });
  e.preventDefault();
});

      



EDIT2.5 : there may be problems with enctype="multipart/form-data"

you need to make some changes: var formData = new FormData(this);

and add some options for the AJAX call

mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false

      

found this example page http://hayageek.com/jquery-ajax-form-submit/

try UPPERCASE / lowercase POST

and then try to delete multipart/form-data

if you don't need it (file upload, etc.)

EDIT3 with multi page form, maybe you should use this in PHP in some cases to access your post data$GLOBALS['HTTP_RAW_POST_DATA']

0


source


Add return false at the end of the script to prevent redirection

0


source