尝试在文本框上输入表单并使用jquery ajax输入新闻不起作用 [英] Trying to submit form on textbox enter press with jquery ajax doesn't work
问题描述
我正在尝试使用jquery和ajax提交表单,但是失败.这是代码:
I'm trying to submit a form using jquery and ajax, but it fails. Here's the code:
$(document).ready(function ()
{
$('.crazytext').keydown(function (event)
{
if (event.keyCode == 13)
{
$.ajax(
{
url: '/sendchat.php',
type: 'POST',
data:
{
'from': $('#from').val(),
'to': $('#to').val(),
'when': $('#when').val(),
'msg': $('#chatty').val()
}
});
}
});
});
这很简单,我想在按下Enter键后提交表单,然后将数据发送到sendchat.php,而无需重新加载页面.这是html:
It's simple, I want to submit the form once enter is pressed and send data to sendchat.php without reloading the page. This is the html:
<form id="send-message-area" method="POST" action="sendchat.php">
<input type="text" name="from" id="from" value="<?php echo $me;?>" hidden>
<input type="text" name="to" id="to" value="<?php echo $other1;?>" hidden>
<input type="text" name="when" id="when" value="<?php echo $date;?>" hidden>
<textarea class="crazytext" name="msg" id="chatty"></textarea>
<input type="submit" name="chat" values="chat" class="crazytext2" hidden>
</form>
如果需要,可以使用sendchat.php的php代码
And if necessary, the php code for sendchat.php
$fromuser = $_POST['from'];
$touser = $_POST['to'];
$when = $_POST['when'];
$msg = $_POST['msg'];
$seen = 0;
$addchat = $db->prepare("INSERT INTO scorp_chats (Fromuser, Touser, Messagetime, Message, Seen) VALUES (:fromuser, :touser, :messagetime, :message, :seen)");
$addchat->execute(array(':fromuser' => $fromuser, ':touser' => $touser, ':messagetime' => $when, ':message' => $msg, ':seen' => $seen));
就是这样,它非常简单,但是失败了.如果我完全删除ajax部分,它可以工作,但是我将重定向到页面,这是不应该发生的.
That's it really, it's super simple but it fails. If I remove the ajax part completely, it works, but I get redirected to the page, which shouldn't happen.
解决方案(感谢Barmar):
$(document).ready(function () {
$('.crazytext').keydown(function (event) { // your input(textarea) class
if (event.keyCode == 13) {
event.preventDefault();
$.ajax({
url: 'sendchat.php', // script to process data
type: 'POST',
data: $("#send-message-area").serialize(), // form ID
success: function(result) {
$("#result").text(result);
}
});
}
});
});
推荐答案
您需要阻止默认的提交操作:
You need to prevent the default submission action:
$('.crazytext').keydown(function (event)
{
if (event.keyCode == 13)
{
event.preventDefault(); // <----
$.ajax(
{
url: '/sendchat.php',
type: 'POST',
data:
{
'from': $('#from').val(),
'to': $('#to').val(),
'when': $('#when').val(),
'msg': $('#chatty').val()
}
});
}
});
这篇关于尝试在文本框上输入表单并使用jquery ajax输入新闻不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!