Submit ajax form and stay on same page not working

时间:2022-11-24 11:10:06

I want to store comments from users in my databse. When a user submits I don't want to redirect them to a new page. I have the following code but it's not working.

我想在我的数据库中存储用户的评论。当用户提交时,我不想将它们重定向到新页面。我有以下代码,但它不起作用。

My HTML code:

我的HTML代码:

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

这是我的PHP文件:

//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 on the submit button it will stay on the same page and show the alert but the data of the input field is not inserted in my database. When I remove the e.preventDefault() the data goes into the database but the page redirects to test.php

当我单击提交按钮时,它将保持在同一页面上并显示警报,但输入字段的数据未插入到我的数据库中。当我删除e.preventDefault()时,数据进入数据库,但页面重定向到test.php

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

尝试了不同的事情,但无法弄清楚。有人可以帮我吗?提前致谢!

3 个解决方案

#1


2  

The form submits and does not stay on the same page because of the action attribute on the form, and the normal submit button.

由于表单上的action属性和正常的提交按钮,表单提交并且不会保留在同一页面上。

Which leads to your .submit() method including .preventDefault() probably not being interpreted after the html is loaded either.

这导致你的.submit()方法,包括.preventDefault()可能在加载html后也没有被解释。

You could do something along the lines of 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 could be something along the lines of:

而javascript可能是这样的:

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

请亲自查看jsfiddle。

You can tell it is working because you get a console error that the request destination is not found - 404 - though the page does not refresh, you stay right where you are...with a proper page to submit to it works fully.

你可以告诉它是否有效,因为你得到一个控制台错误,找不到请求目的地 - 404 - 尽管页面没有刷新,你仍然保持在你所在的位置......有一个适当的页面可以提交给它完全正常工作。

EDIT

I modified the setting of 'data' in the ajax() call so that the form fields are set as a json string to a POST variable [toDB].

我修改了ajax()调用中'data'的设置,以便将表单字段设置为POST变量[toDB]的json字符串。

So in your PHP you would do:

所以在你的PHP中你会这样做:

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

And now your $datas variable is an associative array containing all your form fields names and values. I'm not 100% on this next statement, but you may need to use PHP's stripslashes() method on the POSTED data prior to using json_decode()

现在你的$ datas变量是一个包含所有表单字段名称和值的关联数组。我不是100%在下一个语句,但你可能需要在使用json_decode()之前对POSTED数据使用PHP的stripslashes()方法

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

希望有所帮助

#2


0  

Do it via 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 injections.

是的,使用mysql_real_escape_string($ dataA)清理数据库插入以防止SQL注入。

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

编辑对不起,答案不全(你还需要在表格上使用提交,而不是在文件上)

EDIT2 :) wrong usage of $(this) :)

EDIT2 :)错误使用$(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 can be problems with enctype="multipart/form-data" you need to make some modifications: var formData = new FormData(this); and add some options to AJAX call

EDIT2.5:enctype =“multipart / form-data”可能存在问题需要进行一些修改:var formData = new FormData(this);并为AJAX调用添加一些选项

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

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

发现此页面的示例http://hayageek.com/jquery-ajax-form-submit/

try that UPPERCASE / lowercase POST, and then try to remove multipart/form-data if you dont need it (file upload etc...)

尝试UPPERCASE /小写POST,然后尝试删除multipart / form-data如果你不需要它(文件上传等...)

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

EDIT3与多部分形式,也许您应该在PHP中使用它在某些情况下访问您的发布数据$ GLOBALS ['HTTP_RAW_POST_DATA']

#3


0  

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

在脚本末尾添加return false以防止重定向

#1


2  

The form submits and does not stay on the same page because of the action attribute on the form, and the normal submit button.

由于表单上的action属性和正常的提交按钮,表单提交并且不会保留在同一页面上。

Which leads to your .submit() method including .preventDefault() probably not being interpreted after the html is loaded either.

这导致你的.submit()方法,包括.preventDefault()可能在加载html后也没有被解释。

You could do something along the lines of 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 could be something along the lines of:

而javascript可能是这样的:

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

请亲自查看jsfiddle。

You can tell it is working because you get a console error that the request destination is not found - 404 - though the page does not refresh, you stay right where you are...with a proper page to submit to it works fully.

你可以告诉它是否有效,因为你得到一个控制台错误,找不到请求目的地 - 404 - 尽管页面没有刷新,你仍然保持在你所在的位置......有一个适当的页面可以提交给它完全正常工作。

EDIT

I modified the setting of 'data' in the ajax() call so that the form fields are set as a json string to a POST variable [toDB].

我修改了ajax()调用中'data'的设置,以便将表单字段设置为POST变量[toDB]的json字符串。

So in your PHP you would do:

所以在你的PHP中你会这样做:

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

And now your $datas variable is an associative array containing all your form fields names and values. I'm not 100% on this next statement, but you may need to use PHP's stripslashes() method on the POSTED data prior to using json_decode()

现在你的$ datas变量是一个包含所有表单字段名称和值的关联数组。我不是100%在下一个语句,但你可能需要在使用json_decode()之前对POSTED数据使用PHP的stripslashes()方法

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

希望有所帮助

#2


0  

Do it via 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 injections.

是的,使用mysql_real_escape_string($ dataA)清理数据库插入以防止SQL注入。

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

编辑对不起,答案不全(你还需要在表格上使用提交,而不是在文件上)

EDIT2 :) wrong usage of $(this) :)

EDIT2 :)错误使用$(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 can be problems with enctype="multipart/form-data" you need to make some modifications: var formData = new FormData(this); and add some options to AJAX call

EDIT2.5:enctype =“multipart / form-data”可能存在问题需要进行一些修改:var formData = new FormData(this);并为AJAX调用添加一些选项

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

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

发现此页面的示例http://hayageek.com/jquery-ajax-form-submit/

try that UPPERCASE / lowercase POST, and then try to remove multipart/form-data if you dont need it (file upload etc...)

尝试UPPERCASE /小写POST,然后尝试删除multipart / form-data如果你不需要它(文件上传等...)

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

EDIT3与多部分形式,也许您应该在PHP中使用它在某些情况下访问您的发布数据$ GLOBALS ['HTTP_RAW_POST_DATA']

#3


0  

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

在脚本末尾添加return false以防止重定向