What is the method for triggering two actions within a single linked tag?

I have a link tag structured like this:

<a href="<?php echo base_url().'dashboard' ?>" class="check_session">Home</a>

Upon clicking the "Home" link, it should navigate to the dashboard. At the dashboard page, I want to check if a session exists. If there is an active session, continue to the dashboard. Otherwise, log out.

The JavaScript code I am using for this functionality is as follows:

$(".check_session").click(function() {
    $.ajax({
        url: base_url+"shared/check_session/"+Math.random()+new Date().getTime(),
        success: function(response){     
            if(response == 'out')
            {
                alert('Please login');
                window.location.href = base_url + "logout"; 
            }
        }
    });
});

However, I am facing an issue where the check session function is not being called when the Home link is clicked.

Can anyone help me find a solution to resolve this problem?

Thank you in advance!

Answer №1

To prevent the default behavior of an anchor, you must include event.preventDefault() in your code:

$(".check_session").click(function(e) { // <-----get the event here
    e.preventDefault(); //<--------here stop the default behavior
    var url = this.href; // <---get the url
    $.ajax({
        url: base_url+"shared/check_session/"+new Date().getTime(),
        success: function(response){     
            if(response == 'out'){
                alert('Please login');
                window.location.href = base_url + "logout"; 
            }else{
                window.location.href = url; // <----navigate to it here.
            }
        }
    });
});

The issue arises when clicking on the anchor causes it to navigate to the specified href, preventing your ajax call from being made. It is crucial to use event.preventDefault() when binding events to anchors to avoid this behavior.

Additionally, using new Date().getTime() instead of Math.random() will achieve the same result.

Answer №2

If you want to improve your actions, consider changing a tag within a div.

Additionally, remember to include JavaScript:

$(".check_session").click(function() {
if(session = true)
{
 window.location.href = base_url + "dashboard"; 
}
else
{

    $.ajax({
        url: base_url+"shared/check_session/"+Math.random()+new Date().getTime(),
        success: function(response){     
            if(response == 'out')
            {
                alert('Please login');
                window.location.href = base_url + "logout"; 
            }
        }
    });
}
});

Lastly, make sure your HTML is correct:

<div class="check_session"> class="check_session">Home</a>

Answer №3

Make sure to insert the preventDefault() method at the beginning of the function and include an else statement that redirects to the dashboard if the session is true.

   $(".check_session").click(function(e) {
      var targeturl = $(this).attr('href');
        e.preventDefault();
    $.ajax({
        url: base_url+"shared/check_session/"+Math.random()+new Date().getTime(),
        success: function(response){     
            if(response == 'out')
            {
                alert('Please login');
                window.location.href = base_url + "logout"; 
            }else{
                  window.location.href = targeturl; 
            }
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement the anti-flickering script for Google Optimize in a NextJS/ReactJS environment

While working on a NextJS/ReactJS project, I am experimenting with setting up Google Optimize for some tests. One issue I have encountered is the flickering effect that occurs when Optimize changes visual elements during experiments. To address this probl ...

disabling a submit button

I am new to coding and need help disabling a button on document load. Can someone assist me with this? Here is my current code snippet: $(document).ready(function() { setTimeout("check_user()", 250); }); Your guidance is greatly appreciated! ...

The image file that was uploaded to our S3 storage has been detected

I'm attempting to upload an image created by cropperjs to a DigitalOcean space. To achieve this, I am utilizing a pre-signed URL and performing a put request using Axios. The problem arises when I try to open the uploaded image, as it appears to be ...

Navigating with buttons in the Material UI Drawer

I have implemented a Material UI drawer with some modifications. The original code used buttons, but now I want to navigate to a new page when a button is clicked. For example, clicking on the 'INBOX' button should take me to a page '/new&ap ...

PHP variables that are constantly changing

I recently developed a website that showcases random entries from a database to viewers. Here is the current code snippet I am using: $records = "SELECT * FROM xxx"; $records_query = mysql_query($records); $num_records = mysql_num_rows($records_query); $i ...

Deactivate jQuery hover functionality to address unintended consequences

I am facing an issue with the .hover() function. I have managed to temporarily disable it, but this has caused an unintended side effect that I need help fixing. Here is the link to my fiddle for reference: http://jsfiddle.net/sdPVG/7/ My goal is to disa ...

Adding a dropdown menu to DataTable in Spring MVC: A step-by-step guide

Is there a way to integrate a dropdown list, populated from a database, into the last column of the DataTable within my Spring MVC application? ISSUE: The current setup displays the dropdown list above the table instead of within each row as intended. ...

Generating the data section of $.ajax on the fly

I am trying to dynamically construct the data string, but I'm encountering an issue where it's treating the param variable as a plain string instead. var parameters = "{foo: 'test'}"; $.ajax({ url: 'test.php', ...

Deleting categories and tags in Wordpress is not possible!

I am attempting to modify the default categories within a standard WordPress post without creating any custom taxonomies. Issue: When I try to delete a category or tag from the admin panel, an error message pops up stating "An unidentified error has occur ...

Tips for changing an angular variable string before sending it to a PHP function

When working with AngularJS, I can access form variables within my function like this (for example: s1 = Joe Smith). However, I have a need to update the Indata variable by replacing the a_searchvalue1 with the value stored in s1 but wrapped in quotes. O ...

Refreshing Resteasy utilizing an Ajax POST method

My Ajax post request is not working with Resteasy. I am not getting any errors in Java, but in the browser I see this message: event.returnValue is deprecated. Please use the standard event.preventDefault() instead. OPTIONS https://localhost:8081/TestRes ...

Unable to successfully link filter outcomes with input in AngularJS

Here is the code snippet I am working with: <body ng-app=""> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {nam ...

The login function in Nativescript Vue successfully returns a true value

Hello, I am currently using a function that is quite similar to this one with some minor tweaks here. However, I have encountered an issue when trying to log in to my REST API. Even if I input the incorrect username or password, it still authenticates me ...

Creating PDFs in iOS and Android using Ionic framework

Seeking assistance with resolving this issue. I have researched extensively on Google, jspdf, pdfmake.org, inappbrowser plugins, but have been unsuccessful in getting my Ionic project to function properly. The goal is to create a simple form that includes ...

programming for the final radio button text entry

I am struggling with a form that has 5 radio buttons, including an "other" option where users can manually enter text. The issue I'm facing is that the form only returns the manual entry text and not any of the preset radio values. I need it to work f ...

Incorporating a new element into a JavaScript array

I recently used a vue.js library that has a specific requirement for arrays in this exact format autocompleteItems: [ { text: "Python" }, { text: "HTML" }, { text: "CSS" }, { text: "React ...

Troubleshooting issue: Next.js Material-ui CSS SSR not functioning properly within components

Upon completing my project, I discovered that SSR for Material-ui is not functioning on the page where I utilized functional components. Here is my _document.js file: [Code from _document.js] Example Page: [Code from E ...

Interacting with Django backend via AJAX to trigger Python functions using jQuery/AJAX

Currently, I am developing a small website using Django. Within this project, there are DateTime fields that need to be handled. My intention is to utilize ajax by implementing another button to establish the UTC date while taking into consideration sola ...

Enhancing Bootstrap Date Picker with Custom Buttons: A Tutorial

I am attempting to enhance the datepicker functionality by including a custom button, similar to the today button. My goal is to insert a button at the bottom of the calendar each month. This button will be named "End of the month" and will display the c ...

Arranging Pictures Beside Text Using CSS

I have a puzzling issue that I cannot seem to find an answer for despite the countless times it has been asked. In my footer, there is aligned copyright text, and I am attempting to add 3 logos to the right of it without any line breaks. However, when the ...