[英]Submit form with ajax without reload the page?
I have a problem whatever i do to submit a form using Jquery and Ajax, but it still redirected me to the action page of the form, i don't understand if somethings outside Affected the function or what happen. 我有一个问题,无论我使用Jquery和Ajax提交表单,但它仍然将我重定向到表单的操作页面,我不明白外面的某些事情是影响功能还是发生了什么。 this is my code:
这是我的代码:
<form action="add-niveau" method="POST" class="ajax">
<div>
<input type="text" name="name" placeholder="Your name">
</div>
<div>
<input type="text" name="email" placeholder="Your email">
</div>
<div>
<textarea rows="4" cols="20" name="comment"></textarea>
</div>
<input type="submit" value="send">
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"> </script>
<script>
$('form.ajax').on('submit', function() {
return false;
});
</script>
Other ajax script: 其他ajax脚本:
var ajaxRequest;
function ajaxFunction() {
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
}
function getForm(objButton) {
ajaxFunction();
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
document.getElementById("formTag").innerHTML = ajaxRequest.responseText;
}
}
var buttonValue = objButton.value;
ajaxRequest.open("get", "get-form/" + buttonValue, true);
ajaxRequest.send(null);
}
// Send form using ajax:
$('form.ajax').on('submit', function(e) {
e.preventDefault();
});
You need to add event.preventDefault(); 你需要添加event.preventDefault(); right after click event since you want to prevent the default form submission.
在点击事件之后,因为您想要阻止默认表单提交。
$('form.ajax').on('submit', function(event) { // pass the event to function
event.preventDefault(); // add this line
$.ajax({
url: "test.php",
context: document.body
}).done(function() {
alert('Done!');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.