Why does everytime I put an alert to my ajaxform the page redirects to its php script? but when I remove the alert the ajax doesn't redirect it. I don't want my page to redirect to its php script.
$(document).ready(function(){
$("#save").click(function(){
$("#f1").ajaxForm({
alert("Submit Successful!");
});//ajaxform
});
});
Replace
$("#save").click(function(){
with
$("#save").click(function(e){
e.preventDefault();
pass event as argument and use event.preventDefault()
so page will not be redirect.
You're not using several things properly. Try this:
$(document).ready(function() {
$("#save").click(function(e) {
e.preventDefault(); //cancel default action (not strictly necessary...)
$("#f1").ajaxForm(function() { //N.B. 'function() ' added - before it was an object!
alert("Submit Successful!");
});
});
});
trying stopping the default event behavior.
$("#save").click(function(e){
e.preventDefault();
Use return false
: to stop the request to server
$(document).ready(function () {
$("#save").click(function () {
$("#f1").ajaxForm(function(){
alert("Submit Successful!");
return false;//add return false to stop the request to server
}); //ajaxform
});
});
It is the normal behavior (if the clicked element is an anchor tag pointing to another page): you click a link and it redirects your page.
If you want to use that link as a button and bind a certain action to it, you should definitely stop the normal behavior of the link: prevent it from redirecting the page.
This is achievable in many ways, but the best one (at least from a semantic point of view) is to call the preventDefault
method on the actual click event:
$('a').on('click', function(event){
// prevents the normal behavior of this "click" action
// in this case, it prevents the link from changing the url
event.preventDefault();
//.. your logic here
});
Add preventDefault()
or return false;
.
$("#save").click(function(e) {
$("#f1").ajaxForm({
alert("Submit Successful!");
});//ajaxform
e.preventDefault();
//or
return false;
});
Try this use preventDefault()
$(document).ready(function(){
$("#save").click(function(e){
//Stay in the same page
e.preventDefault();
$("#f1").ajaxForm({
alert("Submit Successful!");
});//ajaxform
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.