Answer the question
In order to leave comments, you need to log in
How to make an ajax request before following a link?
Hello!
There is a task to track the click on certain links on the page and record the data on these clicks in the storage.
Suggested scenario:
$(document).ready(function () {
jQuery(".class_name a").click(function(){
pushClickEvent(this);
return false;
});
});
function pushClickEvent(element){
jQuery.ajax({
type: "POST",
dataType: "json",
url: "some_url",
data: "some_url",
success: function(response){
window.location = $(element).attr('href');
}
});
}
Answer the question
In order to leave comments, you need to log in
After clicking on the button, call a function in which asynchronous ajax performs the actions you need and if the request is successful, open the link you need.
function pushClickEvent(element){
jQuery.ajax({
type: "POST",
async: true,
dataType: "json",
url: "some_url",
data: "some_url",
success: function(response){
window.location = $(element).attr('href');
}
});
}
...
jQuery(".class_name a").click(function(e){
e.preventDefault();
pushClickEvent(this);
...
it's not entirely clear what you are trying to do, but before sending ajax, you can execute the function
beforeSend - fires before sending the request
error - if an error occurred
success - if no errors occurred
complete - fires at the end of the request
https://habr.com/ru/post /42426/
function pushClickEvent(element) {
jQuery.ajax({
type: "POST",
dataType: "json",
url: "some_url",
data: "some_url",
success: function(response) {
//code
},
beforeSend: function(xhr) {
//code
}
});
}
Thanks to everyone for the answers, unfortunately I still had to do it through the "rolling" of the label in the GET parameters (it turned out to be easier this way). The reason - in the process of research, scenarios were revealed in which users can open a link to a new window through the context menu and even by dragging the link to a new tab.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question