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;
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安装完tensorflow,import tensorflow as tf后报错,如何解决?
  • ¥15 ultralytics库导出onnx模型,模型失去预测能力
  • ¥15 linux下点对点协议连接2个USB串口的硬件流量控制问题
  • ¥15 SQL数据自动生成问题
  • ¥15 设密码后无法访问他人的共享文件
  • ¥15 浏览器打不开学校网页
  • ¥100 android开发打不开相册,不弹出授权信息,请问怎么解决?
  • ¥15 我想通过python处理sybase IQ库的一些数据,但是不知道sybase IQ库怎么连接,之前连接都是用linux上的 dbisql
  • ¥15 安装llama-cpp-python==0.1.83失败
  • ¥20 管道轴向耦合水击问题