Reputation: 1874
I want to add ajax call on hyperlink tag "a
", this ajax will only send some info to server and I don' have to get any return.
I tried something like this:
document.querySelector("#myId").onclick = function() {
$.ajax({
url: 'path',
type: 'post',
data: {key: 'value'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
});
}
And I found that, if my "a
" tag with a href-link like
<a href="https://www.google.com" id="myId">click</a>
My server WON"T get any info, and my fail callback function of ajax was triggered, but if I remove the href-link or replace it with #
like
<a href="#" id="myId"></a>
<a id="myId"></a>
my server WILL get the info I send, and of course my success callback funciton was triggered
The fail callback function didn't return any error message, just a simple word error
Does anybody know what's going on and how to change the page and send ajax call in the same click?
By the way, I'm not prefer to put something like
window.location.href = "https://www.google.com.tw"
in my success callback function, because in this case I'm maintain others' codes, I prefer to append my code down below rather than modified the already exist one, thanks!
Upvotes: 2
Views: 3124
Reputation: 67525
First you should prevent the default behaviour (redirection) by adding preventDefault()
:
e.preventDefault();
Hope this helps.
document.querySelector("#myId").onclick = function(e) {
e.preventDefault();
$.ajax({
url: 'api_url',
type: 'post',
data: {key: 'value'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://www.google.com" id="myId">click</a>
Upvotes: 1