【问题标题】:How to To Submit Form data with jquery ajax without refresh the page and get data on request page如何在不刷新页面的情况下使用 jquery ajax 提交表单数据并在请求页面上获取数据
【发布时间】:2019-02-24 22:43:21
【问题描述】:

她是我的密码 HTML

<form id="msg_form">
<input type="text" name="msg_text">
<button type="submit" name="send">Send</button>
</form>

AJAX

$(function () {

    $('#msg_form').on('send', function (e) {

      e.preventDefault();
      $.ajax({
        type: 'POST',
        url: 'msg.php',
        data: $('#msg_form').serialize(),
        success: function () {

        }
      });

    });

  });

现在我想在请求页面上获取数据 如何发送表单数据并在 anthor 页面上接收它 PHP 代码

   $msg_text=$_POST['msg_text'];
   $receiver_id=$_POST['sender_id'];
   $sender_id=$_SESSION['u_id'];
   $sql="INSERT INTO massges (msg_text,sender_id,receiver_id) values('$msg_text', '$sender_id', $receiver_id)";
   $run=mysqli_query($con,$sql);

【问题讨论】:

  • 您使用什么语言接收数据?
  • 我想用 PHP 来接收数据
  • 好的,所以为了让一些 PHP 开发人员参与进来,你应该用 PHP 标记这个问题,然后声明你希望能够用 PHP 检索表单数据。此外,请展示您迄今为止提出的任何 PHP 代码。
  • @lipumuna 看到你的评论,我马上有东西给你。你有任何可以发布的php代码吗?
  • 是的,我已经发布了,现在看到

标签: jquery ajax


【解决方案1】:

好的,这是一个近似值。我对数据字段所做的更改是在 ajax 请求中发送回数据的正确方式。

jQuery

$(function () {
    $('#msg_form').on('send', function (e) {
      e.preventDefault();
      $.ajax({
        type: 'POST',
        url: 'msg.php',
        data: msg_text: $('input[name="msg_text"]'), /*And if you're posting back anything else from the page, sender_id possibly, define same way*/
        success: function () {
          alert('Posted successfully');
        }
      });
    });
  });

php 也许比它需要的更优雅一点,但我不确定你已经走了多远,而且,同样,它更正确

if($_SERVER['REQUEST_METHOD'] == "POST"){
    if($_POST['msg_text'] != '' && $_POST['sender_id'] != '' && $_SESSION['u_id'] != ''){
        $db_connection = sql_connect();
        if($db_connection->connect_errno){
            echo "Failed to connect to db";
        } else {
            $msg_text = $_POST['msg_text'];
            $receiver_id = $_POST['sender_id'];
            $sender_id = $_SESSION['u_id'];
            $sql = "INSERT INTO `massges` (`msg_text`,`sender_id`,`receiver_id`) values('$msg_text', '$sender_id', $receiver_id)";
            if($db_connection->query($sql) === true){
                echo "Successfully inserted data";
            } else {
                echo "Data not inserted";
            }
        }
        $db_connection->close();
    }
}
//connects to db, return true/false for connection status
function sql_connect(){
    return new mysqli("localhost", "user", "password", "database", /*PORT*/ 3306);
}

如果您还可以向我提供您遇到的任何错误或遇到的问题,我可能会提供更多信息。

【讨论】:

  • 我想在mysql中插入数据并且不返回任何东西
  • 什么都没有发生
猜你喜欢
  • 1970-01-01
  • 2012-07-23
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多