I am loading data from URL inside a TAB div, data loads successfully on first request/click but on 2nd request/click it goes to the target link and doesn't populate the target DIV.
Anchor:
<li><a data-toggle="tabAjax" href="http://site.cx/admin/get-coach-stylish-view?userId={{userId}}" id="ajax_tab" class="media_node active span" data-target="#coach-view-stylish-ajax" rel="tooltip">Coach View (Stylised)</a></li>
Div to populate with DATA:
<!-- Coach View Stylised -->
<div id="coach-view-stylish-ajax">
</div>
<!-- Coach View Stylised End -->
JS:
<script>
$('[data-toggle="tabAjax"]').click(function(e) {
e.preventDefault();
var $this = $(this),
loadUrl = $this.attr('href'),
target = $this.attr('data-target');
$.get(loadUrl, function(data) {
$(target).html(data);
});
$this.tab('show');
return false;
});
</script>
1- try to put a debugger in your code, and check that the code is being called on 2nd click. If not, then you need to rebind the click event.
2- You can try this way
<li><a data-toggle="tabAjax" href="#" data-href="http://site.cx/admin/get-coach-stylish-view?userId={{userId}}" id="ajax_tab" class="media_node active span" data-target="#coach-view-stylish-ajax" rel="tooltip">Coach View (Stylised)</a></li>
make href="#" and store url in data-href="..."
and in your javascript
<script>
$('[data-toggle="tabAjax"]').click(function(e) {
e.preventDefault();
var $this = $(this),
loadUrl = $this.attr('data-href'), //change href to data-href
target = $this.attr('data-target');
$.get(loadUrl, function(data) {
$(target).html(data);
});
$this.tab('show');
return false;
});
</script>
Related
I have 3 tabs and on 3rd tab click I'm loading data into the 3rd tab, but once the data is loaded and i click the 3rd tab it loads data twice i.e send request 2 times and when I click the tab 3rd time it doubles the request and send 4 requests and so on.
My Code:
// Separate Ajax call for coach stylish view Data
$(document).on( "click", '.ajaxTab' , function( e ){
e.preventDefault();
var $this = $(this),
loadUrl = $this.attr('data-href'),
target = $this.attr('data-target');
$.get(loadUrl, function(data) {
$(target).html(data);
});
$this.tab('show');
return false;
});
Tab link:
<li><a class="ajaxTab" data-toggle="tabAjax" href="#"
data-href="<?php echo $this->CxHelper->Route('eb-admin-get-coach-stylish-view') ?>?userId={{userId}}"
data-target="#coach-view-stylish-ajax"
rel="tooltip">Coach View (Stylised)</a>
</li>
Use one instead of on. [http://api.jquery.com/one/][1]
$(document).one( "click", '.ajaxTab' , function( e ){
e.preventDefault();
var $this = $(this),
loadUrl = $this.attr('data-href'),
target = $this.attr('data-target');
$.get(loadUrl, function(data) {
$(target).html(data);
});
$this.tab('show');
return false;
});
[1]: http://api.jquery.com/one/
jQuery off method to remove existing click event handler http://api.jquery.com/off/
$(document).off().on( "click", '.ajaxTab' , function( e ){
e.preventDefault();
var $this = $(this),
loadUrl = $this.attr('data-href'),
target = $this.attr('data-target');
$.get(loadUrl, function(data) {
$(target).html(data);
});
$this.tab('show');
return false;
});
Perhaps the click is being called in an incremental value, i usually see that when i set click listeners in an ajax success method.
you might want to unbind events from the .ajaxTab
$(document).on( "click", '.ajaxTab' , function( e ){
$('.ajaxTab').unbind();
.........//the other logic
});
unbind removes click listeners from the element
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.
I'm currently loading my page data dynamically clicking on an element like this:
<a onclick="load('url_of_data')">Some Text</a>
But for a better UX I now want to have an element like this:
Some Text&
and then just use preventDefault like this;
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
load(href);
});
I got this code from this question.
But it does not work, the site is still reloading and not running the function.
I now apply the click handler everytime the dynamic content was loaded and it works fine.
You need to add return false at the end of your function
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
load(href);
return false;
});
You will need to specify the container div to which the content will be loaded into.
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
//Replace "self" with the container you want to load the content into, e.g. $("#myDiv").load(href);
self.load(href);
});
I Think this will make the work.
$('a').click((e) => {
e.preventDefault();
const href = $(e.currentTarget).attr('href');
window.location.href = href;
});
I just needed to reapply the click handler everytime the dynamic content was loaded.
Now it's working fine
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
window.location.assign(href);
});
It helps you
I am working on an AJAX pagination and I made it by using this code.
$(document).ready(function() {
var pagination = $("#pagination");
var url = urlProviderOffers;
updateContent(function(json) {});
pagination.on('click', "ul a", function(e) {
e.preventDefault();
var page_to_visit = $(this).text();
updateContent(function(json) {});
pagination.find('ul li').removeClass('active');
$(this).parent().addClass('active');
});
function updateContent(callback, page_to_visit) {
page_to_visit = typeof(page_to_visit) != 'undefined' ? page_to_visit : 1;
$.ajax({
url: url,
data: {
page: page_to_visit
}
}).done(function(json) {
if (json.total > 1) {
pagination.find("ul li:nth-child(1)").addClass('active');
}
callback(json);
});
}
url = template_url.replace(/provider_id_to_change/, providerID);
return url;
}
});
<div id="pagination">
<ul class="pagination">
<li class="active">1
</li>
<li>2
</li>
<li>3
</li>
</ul>
</div>
The problem I am having is that, any time I click on one of the links of the pagination, a function is called and inside this function I change the active link been visited by the user.
For instance, when my page is loading, the function updateContent sets the current page been visited to 1. And after clicking on another link of the pagination, I remove all the added class and add a new active class to the selected link.
In my case anytime, when a link is clicked, is set the class of the selected link to active and automatically remove the added class and set the active class to the first link.
kindly help me solve this problem
how can i select the current link via jquery if I have a div like this:
<div id='navigation'>
<a href='users/home'>home</a> |
<a href='projects/browse'>home</a>
<a href='discussions/browse'>home</a>
<a href='search/dosearch'>home</a>
</div>
Note I've tried:
$(document).ready(function(){
$("#navigation a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
clicked.addClass('selected');
});
});
But when I click on a link it selects a link and adds the class .selected but it reloads the page in order to navigate to a page and then it all disappears. Any tips?
Thanks
This should work:
$(document).ready(function() {
var loc = window.location.href; // The URL of the page we're looking at
$('#navigation a').each(function() {
if (loc.indexOf(this.href) !== -1) { // If the URL contains the href of the anchor
$(this).addClass('selected'); // Mark it as selected
}
});
});
It basically loops over the navigation items, and if the URL of the current page contains the href of the anchor, it adds the class selected to the anchor.
Yep, take the event from your click() callback arguments and use e.preventDefault(); (see there).
Or return false.
Or add a target='_blank' attribute to your links so that they open the link in some other page or tab, if you still want the link to be opened by the browser somewhere.
$(document).ready(function(){
$("#navigation a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
clicked.addClass('selected');
return false;
});
});
Don't forget to return false!