我想发送一个表单,以便在发送表单时不会刷新页面。 现在,当我按下提交按钮即时运行此代码:
<?php
if (isset($_POST['send_this_message']) == 'yes')
{
echo "yes this is just example and working";
}
?>
<form method="post" action="">
<input type="submit" name="send_this_message" value="yes">
</form>Now how can send this form but without page refresh with jquery. I have seen several examples but they are all calling external files.. Something like this.
<script>
$(function () {
$("#send").click(function () {
$.ajax({
type: "post",
url: "send.php",
data: $("#myform").serialize(),
success: function (response) {
if (response == "done") {
alert("Form submitted successfully!");
} else {
alert("Form submission failed!");
}
},
error: function (response) {
alert(response);
}
});
});
})();
</script>
上面的代码对我不起作用。我的意思是我需要以某种方式按下按钮时执行该设置。有什么想法吗?
祝所有庆祝的人们圣诞快乐,新年快乐!答案 0 :(得分:2)
由于您希望在没有页面刷新的情况下发送数据,请使用Ajax将数据发送到您的php文件:(例如)
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'post.php', // here your php file to do something with postdata
data: $('form').serialize(), // here you set the data to send to php file
success: function (data) {
alert('form was submitted');
}
});
e.preventDefault();
});
});
</script>
答案 1 :(得分:0)
我不知道你是否理解你的问题 但是,您需要在
中为您的attribut操作设置一个值 <form method="POST" action="">
例如
<form method="POST" action="responseForm.php">
答案 2 :(得分:0)
您正在选择
$("#send")
它不存在 将ID添加到按钮
<input id="send" type="submit" name="send_this_message" value="yes">
您还需要使用preventDefault()
来停止传播
答案 3 :(得分:0)
假设您的脚本名为script.php:
<?php
if (isset($_POST['send_this_message']) == 'yes')
{
// do stuff
echo "done"; // as confirmation for jQuery, see below
die(); // no output the form because ajax function isn't interested in it
}
?>
<form method="post" action="" id="form">
<input type="submit" name="send_this_message" value="yes">
</form>
<script>
$(function () {
$("#form").submit(function (e) {
e.preventDefault(); // prevent the form from being submitted normally
$.ajax({
type: "post",
url: "script.php",
data: $(this).serialize(),
success: function (response) {
if (response == "done") {
alert("stuff done");
} else {
alert("isset wasn't true");
}
},
error: function (response) {
alert("server returned a 500 error or something");
}
});
});
})();
</script>