提交表单而不重新加载页面

时间:2017-02-06 16:24:26

标签: php jquery html forms

我知道有很多问题,例如this one,但我仍然无法使其正常运作。甚至评论我应该做些什么来使这个正确是绰绰有余,因为我理解像80%的jQuery ..

<form action="meddelanden.php" id="fromen2" method="post">
    <input type="text" name="message" id="type" autocomplete="off" placeholder="type your chat message">
    <input class="lg" type="submit" name="submit" value="Send">
</form>

Meddelanden.php

<?php
    session_start();
    $meddelanden = $_POST['message'];
    $username = $_SESSION['user'];
    include ("connect.php");
    $sql = $con->prepare('INSERT INTO messages (message,username) VALUES (?,?)');
    $sql->bind_param("ss",$meddelanden,$username);
    $sql->execute(); 
    $sql->close();
    $con->close(); 
?>

脚本(为我的头脑搞砸了)

$('#fromen2').submit(function(){

    $.ajax({
        type: 'POST',
        url: meddelanded.php,
        data: { 
            user: username,      // <-- is this what i should write in data?!
            message: message     // <-- and this?!
        },
        success: function(msg){                        
            alert('Message Sent');
        }
    });

    return false;
});

所以,我的问题是我应该在data:写的,我不知道我应该在那里输入什么!任何人都可以帮助我,还是其他让它无效的东西?

2 个答案:

答案 0 :(得分:1)

尝试这样的事情。不过,你可能不得不乱用它。我首先阻止表单在您按下提交按钮时自动提交,然后我将用户输入的值用于消息,并在messageInput中输入data的值。希望这会有所帮助。

$('#fromen2').submit(function(e){
 e.preventDefault();
 var userMessage = $('#messageInput').val();

 $.ajax({
  type: 'POST',
  url: meddelanded.php,
  data: { 
    //You dont need to send user data becaues you are setting the user variable with $_SESSION in php file
    message: userMessage     
  },
   success: function(msg){


   alert('Message Sent');

      }
   });

return false;
});

HTML

<form id="fromen2" method="post">
        <input type="text" id = "messageInput" autocomplete="off" placeholder="type your chat message">
        <input class = "lg" type="submit" name="submit" value="Send">
    </form>

或者,不是使用.submit()作为事件,而是可以向onclick事件添加一个函数,该事件将从表单中检索数据并使用AJAX将数据发布到PHP脚本中。

$('#submitButton').on('click', function(e){
e.preventDefault();
var userMessage = $('#messageInput').val();

$.ajax({
 type: 'POST',
 url: meddelanded.php,
 data: { 
   //You dont need to send user data becaues you are setting the user    variable with $_SESSION in php file
   message: userMessage     
 },
  success: function(msg){


  alert('Message Sent');

     }
  });
});

HTML

<form id="fromen2">
    <input type="text" id = "messageInput" autocomplete="off" placeholder="type your chat message">
    <input class = "lg" id="submitButton" name="submit" value="Send">
</form>

答案 1 :(得分:0)

使用jQuery serialize序列化表单数据:

$('#fromen2').submit(function(){

    $.ajax({
        type: 'POST',
        url: meddelanded.php,
        data: $(this).serialize()
        success: function(msg){

           alert('Message Sent');
        }
    });

    return false;
})