提交ajax表单并保持同一页面不起作用 [英] Submit ajax form and stay on same page not working

查看:85
本文介绍了提交ajax表单并保持同一页面不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

    }

});
});

这是我的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();

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

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

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

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

推荐答案

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

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

这导致您的 .submit()方法,包括<$ c加载html后,可能无法解释$ c> .preventDefault()。

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

您可以采取以下措施:

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>

javascript可能是这样的:

And the javascript could be something along the lines of:

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

参见 jsfiddle 为自己。

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

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.

编辑

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

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

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

So in your PHP you would do:

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

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

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

ie:

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

希望有帮助

这篇关于提交ajax表单并保持同一页面不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆