[英]Passing data to PHP via Ajax without using a submit button
I've had a look around and unfortunately the solutions I've found on the site don't appear to address my issue below. 我四处张望,很遗憾,我在网站上找到的解决方案似乎无法解决以下问题。
Basically I'm doing a project where I need to effectively set up a diary - the user writes in a textarea element and this is passed via PHP to a database and stored for the user. 基本上,我正在做一个需要有效设置日记的项目-用户写入textarea元素,然后通过PHP将其传递到数据库并为用户存储。 In the lecturer's video, it appears he's doing without using a submit button (even if he's not, I think it'd be an interesting thing to learn how to do).
在讲师的视频中,似乎他在做操作而没有使用提交按钮(即使他没有,我认为学习如何做也是一件很有趣的事情)。
I'm having some issues though. 我有一些问题。 Here's my PHP:
这是我的PHP:
<?php
session_start();
if(array_key_exists("id", $_COOKIE)) {
$_SESSION['id'] = $_COOKIE['id'];
}
if(array_key_exists("id",$_SESSION)) {
echo "Logged in: <p><a href='secretDiaryFinal2.php?logout=1'>
Log out</a></p>";
} else {
header("Location: secretDiaryFinal2.php");
}
/* I'm putting in the database update later, for now I just wanted to check if I could
actually create the POST variable below*/
$msg = "";
if(array_key_exists('diaryEntry',$_POST)) {
$msg = $_POST['diaryEntry'];
} else {
$msg = "Some kind of PHP error";
}
?>
The relevant HTML: 相关的HTML:
<body>
<div id="testDiv">
<? echo $msg ?>
</div>
<div class="container" id="diaryArea">
<form method="post">
<textarea id="diary" value=""></textarea>
</form>
</div>
The relevant JQuery (I'm very weak on Ajax and I suspect there's a lot of issues here - also note the url I'm using is actually in the same script as the JQuery, I'm not certain if that works?) is below. 相关的JQuery(我在Ajax上非常弱,我怀疑这里有很多问题-还请注意,我使用的url实际上与JQuery在同一脚本中,我不确定是否可以使用?)是下面。
The basic idea is that every time the user types, the database should be updated (I realise this is a lot of calls to the server, I'll probably replace it with a timed command): 基本思想是,每次用户键入时,都应更新数据库(我意识到这是对服务器的大量调用,我可能会用定时命令替换它):
<script type="text/javascript">
$("#diary").keyup(function () {
var dataString = $("#diary").val();
$.ajax({
type: "POST",
url: "loggedInPageFinal.php",
data: ({diaryEntry:dataString}),
success: function(data) {
console.log(data);
}
});
return false;
});
</script>
Many thanks in advance and apologies for my poor code! 在此先感谢和歉意!
var DataString = $("#diary").val();
$.post( "loggedInPageFinal.php",{dataString:DataString }, function( data ) {
console.log(data);
});
Your ajax script actually does work. 您的ajax脚本实际上可以正常工作。 But your php code isn't returning anything.
但是您的php代码未返回任何内容。 put
exit($msg);
放置
exit($msg);
at the end of the code and see what happens. 在代码末尾,看看会发生什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.