weixin_33737774 2015-10-27 15:57 采纳率: 0%
浏览 28

Ajax POST和php查询

Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.

jQuery:

$(document).ready(function() {

        $(document).on('submit', 'form#shoutboxform', function () { 

            $.ajax({  
              type: 'POST',  
              url: 'shoutboxform.php',  
              data: form.serialize(),
              dataType:'html',  
              success: function(data) {alert('yes');},
              error: function(data) {

              alert('no');
              }
            });  
            return false;  

              });

        }); 

PHP:

<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
    $sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
    if(!empty($sboxmsg)) {
        $addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
    }
}

And HTML:

<form method="post" id="shoutboxform" action="">
                <input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
                <input type="submit" name="subsbox" id="shbox_button" value="Post">
            </form>

When I submit anything, it just reloads the page and nothing is added to the database.

  • 写回答

2条回答 默认 最新

  • 旧行李 2015-10-27 16:05
    关注

    Prevent the default submit behavior

       $(document).on('submit', 'form#shoutboxform', function(e) {
      e.preventDefault();
      $.ajax({
          type: 'POST',
          url: 'shoutboxform.php',
          data: $(this).serialize(),
          dataType: 'html',
          success: function(data) {
              alert('yes');
          },
          error: function(data) {
    
              alert('no');
          }
      });
      return false;
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站