jQuery: How to post data after clicking on a link without ajax? - javascript

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.

Related

How to register a click but still have a normal ahref

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.

Monitoring page use with jQuery/javascript

I plan to add some basic user usage of multiple html pages. To achieve this I want to introduce as little code changes to existing pages as possible. Here is my approach :
Import .js file that contains operations to add listeners to the page and when an event is fired then invoke a function :
<title>myTitle</title>
<input id="click" type="submit" value="click"/>
<input id="test" type="textbox" value="test"/>
<a id="href">href</a>
$('a').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
$('input').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
function sendData(dataToSend) {
console.log('Sending data \n '+dataToSend)
}
for now sendData is just a dummy function, but I plan to modify this to send an ajax request to server endpoint with the dataToSend value.
Is there an alternative method of monitoring what the user clicks instead of coding a tags and input tags ? There may be other input types that I'm not aware of that may get clicked that will not be tracked ?
fiddle :
http://jsfiddle.net/g2Rxc/167/
Because click events may be added after you've imported your listener code, you'll want to use event delegation on the document element.
Since you're running jQuery v 1.6, you'll need to use the delegate method:
$(document).delegate('*', 'click', function(e) {
var linker = $(this).attr('id'),
title = $(document).find("title").text(),
url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
return false;
});
Fiddle 1
Later versions of jQuery handle event delegation using the on method:
$(document).on('click', '*', function(e) {
var linker = $(this).attr('id'),
title = $(document).find("title").text(),
url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
return false;
});
Fiddle 2
I see that your click functions do the same thing so you can nest all the elements in a single click event:
$('a,input,textare,..,..').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
Try:
$("body").find("*").on("click",function()...
You just need to plan what do you want to track, before write the code. By doing that you are going to find which elements and events you really want to track. With that in mind you will write something like:
$('everyElementSeparatedByComma').on('everyEventSeparatedByComma', function(){
...
});
A real example:
$('a, input, textarea, form').on('click, change, keypress, submit', function(){
...
});

Generate url only when anchor is clicked

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>

identify link id's clicked and pass it to javascript function

my js file has
$('#opt_no').click(function() {
$('#sample6').append('<br>Employee Number:').append($("#dynamic").val());
});
$('# opt_yes').click(function() {
$('#sample7').append('<br>Employee Number:' ).append($("#dynamic").val());
});
opt_no and opt_yes are links on my html page.
when user click on submit button, i want to identify on which link he has clicked and pass this link id to onClick function of submit button
Hard to say without the rest of the code. Do you want something like this?
$('#opt_no').click(function() {
$('#sample6').append('<br>Employee Number:').append($("#dynamic").val());
$("#submitlink").attr("href", $(this).attr('id'));
});
Assuming only one link can be clicked, or that the most recent clicked link is the only one you care about, then you can store the id values in a global variable. This can then be accessed from within any other function, such as your submit click event.
var linkId;
$('#opt_no').click(function() {
linkId = $(this).attr('id');
$('#sample6').append('<br>Employee Number:').append($("#dynamic").val());
});
$('# opt_yes').click(function() {
linkId = $(this).attr('id');
$('#sample7').append('<br>Employee Number:' ).append($("#dynamic").val());
});
$('#submitButton').click(function() {
//do something with linkId
});
you ca n get id using this code
$(this).attr('id');

Making link to go somewhere else than its default href

I want to grab the link text and append it to the URL and open the new URL with querystring added Onclick of the Original Link..How do I get the link text using javascript or jquery?
<a href="www.mysite.com/search.aspx?kwd=" onClick="location.href='http://mysite.com/search.aspx?kwd='+ Grab text 'kangaroo' and append here as QueryString>Kangaroo</a>
You can access the current anchor through this. The text can be then had through this.innerHTML.
Something like this...
Kangaroo
$('.your-url').click(function(event) {
event.preventDefault();
window.location= $(this).attr('href') + encodeURIComponent($(this).text());
});
I noticed that none of the other answers were encoding the text in the link to be a query-string parameter.
Inline (like your example) would look like this:
Kangaroo
return false should be unnecessary because once you change the location object scripts stop running and the page changes.
UPDATE
You can use $.trim() to:
Remove the whitespace from the beginning and end of a string.
Source: http://api.jquery.com/jquery.trim/
$('a.your-url').click(function(e) {
e.preventDefault();
url = $(this).attr('href') + $(this).text();
location.href = url;
});
To send the page to the link's href + text when clicked, this should work:
$("a").click(function(){
location.href = $(this).attr("href") + $(this).text();
return false;
});
But why not just set the hrefs correctly when the page loads, and get rid of all these onclick handlers altogether?
$("a").each(function(i, el) {
var $el = $(el);
$el.attr("href", $el.attr("href") + encodeURI($el.text()));
});
jQuery example:
$('a.link').click(function () {
var $this = $(this),
href = $this.attr('href');
window.location = href + encodeURIComponent($this.text());
event.preventDefault();
return false;
});
Demo

Categories