On a webpage I have several links to items, for example:
View item 1
View item 2
View item 3
For SEO reasons I want to have a normal ahref, but when someone clicks on the link, I want to register the click in a database so I can see how many times an item has been clicked on.
I think somehow with an Ajax call that will register the click in the database, but not sure.
This is how I would have done it
Register a click event.
Prevent its default behavior with event.preventDefault();
Save href attribute's value
Send an ajax and do the stuff
Now redirect to the url specified in href with location.href = href;
$(".aLinks").on('click',function(event){
event.preventDefault();
var href = $(this).href;
$.ajax(...).success(function(){
//Do something if you want
location.href = href;
})
});
View item 1
You can add an onclick handler and prevent the default behavior using the event.preventDefault.Inside this function make the request to save the data to db
function test(e) {
event.preventDefault();
console.log(e.target.href);
return true;
}
View item 1
View item 2
View item 3
you can set id to a tag and add a event listener to that then call service on back-end to insert to db
<a class="some-btn" id="btn-1" href = "/view-item.php">View item 1</a>
<a class="some-btn" id="btn-2" href = "/view-item.php">View item 2</a>
<a class="some-btn" id="btn-3" href = "/view-item.php">View item 3</a>
<script>
$('.some-btn').on('click',function(){
var id = $(this).attr('id')
//... then send id to your service with ajax or axios
})
</script>
<a> tags can be given an href attribute or an onclick attribute, or both. The onclick attribute can point to a JavaScript function defined elsewhere:
<body>
<script type="text/javascript">
function logClick() {
console.log("Clicked!");
}
</script>
<a onclick="logClick()">Click Here!</a>
</body>
This attribute can be assigned in JavaScript with the Element.addEventListener function:
HTML:
<a id="link">Click Here!</a>
JavaScript:
function logClick() {
console.log("Clicked!");
}
const aTag = document.getElementById("link");
aTag.addEventListener("click", logClick);
So create your POST request in a JavaScript function, and pass the function somehow to the HTML <a> element's click event.
I think the most straightforward approach is:
register a click event handler on the a elements
prevent the default behavior for the click event.
store the destination page in a new variable
and then do you stuff in your event handler, like XHR
after finishing you stuff, set the window.location.href property to the destination you saved in step 3.
Here's some code without using jQuery:
const manyA = [...document.querySelectorAll("a")];
manyA.forEach(a => {
// register the click event
a.addEventListener("click", event => {
// prevent the default behaviour
event.preventDefault();
// get destination for link
const destination = event.target.getAttribute("href");
// do the XHR stuff
const xhr = new XMLHttpRequest();
xhr.open('GET', 'myservice/username?id=some-unique-id');
xhr.onload = () => {
if (xhr.status === 200) {
alert('User\'s name is ' + xhr.responseText);
/// redirect your user to the destination page
window.location.href = destination;
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
});
});
Some Link
Some Other Link
Thanks everyone for your help!
This is what I've done and works:
<a class="some-link" id="1" href = "/view-item.php?id=1">View item 1</a><br>
<a class="some-link" id="2" href = "/view-item.php?id=2">View item 2</a><br>
<a class="some-link" id="3" href = "/view-item.php?id=3">View item 3</a><br>
<script>
$('.some-link').on('click',function(){
var id = $(this).attr('id')
$.ajax({
url: "/click-count.php",
type: "GET",
cache: false,
data: {
method: "UpdateClickCount",
id:id
},
dataType: "json",
success: function (data) {
}
});
})
The click-count.php is called where the database is updated.
Related
I have multi link to delete via ajax:
<a id="id-1">link1</a>
<a id="id-2">link2</a>
<a id="id-3">link2</a>
<a id="id-4">link2</a>
...
this is a simplified of my code:
$(document).on("click", "[id^=id-]",function(event) {
event.preventDefault();
var btnid = this.id;
alert('1:'+btnid );
// a dialog confirm to aks delete in bootstrap
$("#confirmbtn").on( "click", function(event) {
alert('2:'+btnid );
});
})
when I refresh page for first one I got this in alert:
(click on <a id="id-1">link1</a>)
1:id-1
2:id-2
but for second,third and ... I got wrong!
for example for second:
(click on <a id="id-1">link2</a>)
1:id-2
2:id-1
2:id-2
the third:
(click on <a id="id-1">link3</a>)
1:id-3
2:id-1
2:id-2
2:id-3
I expect
1:id-3
2:id-3
can help me to solve that?
As you are binding event handler inside another event handler, a new event handler is getting attached every the element is clicked, thus you are getting the issue. You can use .data() to persist arbitrary data.
$(document).on("click", "[id^=id-]",function(event) {
event.preventDefault();
var btnid = this.id;
alert('1:'+btnid );
$("#confirmbtn").data('id', this.id)
})
// a dialog confirm to aks delete in bootstrap
$(document).on( "click", "#confirmbtn", function(event) {
alert('2:'+$(this).data('id'));
});
You are binding multiple eventhandlers to the button. With each clicked link (link-1, link-2 etc.) you add a new one to the button, but the existing ones remain. To solve this, you could add an event handler to the confirm-button on initialization and use a variable, which tells you anytime, which link was clicked last. You could do this like this:
$(document).ready(function() {
var lastLinkId;
$("#confirmbtn").click(function() {
alert("2: "+lastLinkId);
});
$(document).on("click", "[id^=id-]",function(event) {
event.preventDefault();
lastLinkId = this.id;
alert('1: '+lastLinkId);
});
});
I have a $.post() request named "HasIncreasePoint" and if the data returned from server indicates a success (e.IsSuccess), I want not to open the bootstrap modal dialog, and accomplish the click event process.
$('a[data-toggle="modal"]').on('click', function (event) {
$.post("#Url.Action("HasIncreasePoint")", function (e){
if (e.IsSuccess) {
alert("error!please not to open the modal!");
event.preventDefault();
event.stopPropagation();
$('a[data-toggle="modal"]').off("click");
}else{
// From the clicked element, get the data-target arrtibute
// which BS3 uses to determine the target modal
var target_modal = $(e.currentTarget).data('target');
// also get the remote content's URL
var remote_content = e.currentTarget.href;
// Find the target modal in the DOM
var modal = $(target_modal);
// Find the modal's <div class="modal-body"> so we can populate it
var modalBody = $(target_modal + ' .modal-body');
// Capture BS3's show.bs.modal which is fires
// immediately when, you guessed it, the show instance method
// for the modal is called
modal.on('show.bs.modal', function () {
// use your remote content URL to load the modal body
modalBody.load(remote_content);
}).modal();
// and show the modal
// Now return a false (negating the link action) to prevent Bootstrap's JS 3.1.1
// from throwing a 'preventDefault' error due to us overriding the anchor usage.
return false;
}
});
});
and the HTML code:
<a class="btn-check-in" href="#Url.Action("ReverseCard")" data-toggle="modal" data-target="#myModal" id="btn-sign">
<i></i><span>SignIn</span>
</a>
You can remove data-toggle="modal" attribute and bind click on .btn-check-in class.
Then, whenever you need the modal, open it using javascript (as you already do)
<a class="btn-check-in" href='#Url.Action("ReverseCard")' data-target="#myModal" id="btn-sign">
<i></i><span>SignIn</span>
</a>
JS:
// set a flag to prevent multiple requests:
var waiting = 0;
$('.btn-check-in').on('click', function(event){
event.preventDefault();
if(!waiting){
var myModal = $(this).data('target');
var remote_content = this.href;
$.post('#Url.Action("HasIncreasePoint")').done(function(e){
if(!e.IsSuccess){
// this part seems to be overdone, but I left it as is
// as I don't know what is your reason of loading fresh content each time...
$(myModal).on('show.bs.modal', function(){
$(this).find('.modal-body').load(remote_content);
}).modal('show');
}else{
// it was successful!
}
waiting = 0;
});
}
waiting = "I'm waiting for $.post()";
});
I'm trying to figure out how to change behaviour of a button using AJAX.
When the button is clicked, it means that user confirmed order recently created. AJAX calls /confirm-order/<id> and if the order has been confirmed, I want to change the button to redirect to /my-orders/ after next click on it. The problem is that it calls again the same JQuery function. I've tried already to remove class="confirm-button" attribute to avoid JQuery again but it does not work. What should I do?
It would be enough, if the button has been removed and replaced by text "Confirmed", but this.html() changes only inner html which is a text of the button.
$(document).ready(function () {
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
var id = this.value;
var url = '/confirm-order/'+id;
$.ajax({
type: 'get',
url: url,
success: function (data) {
$this.empty();
$this.attr('href','/my-orders/');
$this.parent().attr("action", "/my-orders/");
$this.html('Confirmed');
}
})
});
});
The event handler will be still attached to the button, so this will run again:
b.preventDefault();
which will prevent the default, which is opening the href. You need to remove the event handler on success. You use the jQuery #off() method:
$(".confirm-button").off('click');
or more shortly:
$this.off('click');
You can add to your success function something like: $this.data('isConfirmed', true);
And then in your click handler start by checking for it. If it's true, redirect the user to the next page.
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
if ($this.data('isConfirmed')) {
... redirect code ...
}
else {
... your regular code ...
}
}
You need to use .on() rather than .click() to catch events after the document is ready, because the "new" button appears later.
See http://api.jquery.com/on/
$(document).ready(function() {
$('.js-confirm').click(function(){
alert('Confirmed!');
$(this).off('click').removeClass('js-confirm').addClass('js-redirect').html('Redirect');
});
$(document).on('click', '.js-redirect', function(){
alert('Redirecting');
});
});
<button class="js-confirm">Confirm</button>
I've got the following links in my page:
<a href='/post/view/12' id='93' class='notification_link'>your post</a>
<a href='/post/view/13' id='112' class='notification_link'>your post</a>
Whenever the user clicks on any of the above links, I need to post the id of the link (e.g. 93) along with the post id (e.g 12) to the (/post/view) page. But I don't want to do this via ajax. I want to be redirected to the /post/view page as if the user has clicked on the link. So far I've come up with the following code, but don't know how to continue. Any advice would be appreciated.
$(document).ready(function(){
$(document).on("click", '.notification_link', setNotification);
});
function setNotification(e){
targetUrl = $(this).attr('href');
id = $(this).attr('id');
$.post(targetUrl, { id: $(this).attr('id'), view_id: "12" }, null);
return false;
};
If you really want to do this without ajax then you can try this...
function setNotification(e){
targetUrl = $(this).attr('href');
id = $(this).attr('id');
$('<form/>').append('<input name="id" value="'+ id +'"/><input name="view_id" value="12"/>').attr('action', targetUrl ).attr('method', 'POST').appendTo('body').submit();
return false;
};
In a similar scenario I used cookies to save the value I didn't want to appear in the URL. Put the handler in the mousedown event so that the cookie will be created before the new page starts to load.
jQuery('a.notification_link').mousedown(function () {
var myid = jQuery(this).attr('id');
//here save in a cookie, you can use your own code to save in a cookie
create_cookie('notification_link', myid, 0);
});
And you can get this value both in the code behind and also in the client side.
Is it possible to assign url to the an anchor only when it got clicked?
Token Link
When the anchor got clicked, it will go to http://example.com/token=xxxxx/
I want to generate token only when it got clicked.
If possible, How?
thanks
you can handle the event and change the href like this.
$("a").on("click", function() {
$(this).attr("href", $(this).attr("href") + "/token=xxxx");
});
you can also directly navigate the user to a different url, without changing.
$("a").on("click", function(ev) {
document.location.href = "//something-different.com";
ev.preventDefault();
return false;
});
Opening the link in another window using jQuery
$(document).ready(function () {
$(".thisClass a").on("click", function(e){
e.preventDefault(); // this prevents going to the original url or default behavior
var changedLink = $(this).attr("href", $(this).attr("href") + "/token=xxxx");
var newUrl = $(changedLink).attr('href');
window.open(newUrl, '_blank');
});
});
// Here is a way to do it with Plain Javascript - i did not test it on all browsers but worked with chrome for example.
// goes in a script.js or in script tags under the </body> element
function changeTheLink() {
event.preventDefault();
var aLink = document.getElementById('theLink');
var theOldLink = aLink.getAttribute("href");
aLink.setAttribute('href', theOldLink + "/token=xxxx");
var theNewLink = aLink.getAttribute("href");
window.open(theNewLink, "_blank");
}
// here is the HTML you owuld have to add an id and an onclick attribute to use this code
<div class="thisClass"><a href="http://thiswebsite.com" id="theLink"
onclick="changeTheLink()">Here is a link</a></div>