Using jQuery to submit data via POST method without having the page reload

I have a link in the footer that, when clicked, jumps to the header with a # in the address bar. Is there a way to prevent this and stay in the footer?

Here is the code snippet:

<a href="#" class="clickIn" id="1" attrIn="Like"><span style="color: #33A13D"><i class="fa fa-hand-o-up"></i></span></a>

$(document).on('click', '.clickIn', function(){
    var $this = $(this);
    var liCount = $('#liCount');
    if($(this).attr('attrIn')=='Like'){
        $.post('page.php',{i:$(this).attr('id'),action:'like'},function(){
            $this.html('done');
            $this.attr('attrIn','');
        });
    }
});

Thank you.

Answer №1

Utilize event.preventDefault() method:

$(document).on('click', '.clickIn', function(e){
    e.preventDefault();
    var $element = $(this);
    var listCount = $('#liCount');
    if($(this).attr('attrIn')=='Like'){
        $.post('page.php',{i:$(this).attr('id'),action:'like'},function(){
        $element.html('done');
        $element.attr('attrIn','');
    });
    }
});

This function prevents the default action of the browser on a specific element. For more information, refer to: http://api.jquery.com/event.preventDefault/

Answer №2

To make your handler more effective, you need to include e.preventDefault() and e.stopPropagation() in it:

$(document).on('click', '.clickIn', function(e){
    e.preventDefault();
    e.stopPropagation();
    var $this = $(this);
    var liCount = $('#liCount');
    if($(this).attr('attrIn')=='Like'){
        $.post('page.php',{i:$(this).attr('id'),action:'like'},function(){
        $this.html('done');
        $this.attr('attrIn','');
    });
    }
});

By adding these lines of code, you will prevent the default action of your link (going to a "#" link) and stop the click event from bubbling up.

Answer №3

To stop the default behavior of an event that has been triggered, you can use the preventDefault method of the event object like so:

$(document).on('click', '.clickIn', function(event){
    var $this = $(this);
    var liCount = $('#liCount');

    // Include this line to prevent default behavior:
    event.preventDefault();

    if($(this).attr('attrIn')=='Like'){
        $.post('page.php',{i:$(this).attr('id'),action:'like'},function(){
            $this.html('done');
            $this.attr('attrIn','');
        });
    }
});

Answer №4

Triggering click event

event.preventDefault();

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

The bottom portion of my page vanishes without a

My footer has the following CSS class: .footer{ border-top:solid 2px #BBB; background : url('../images/footer.png'); font-family : helvetica; font-style : italic; height:9em; clear: both; color: black; wid ...

Choosing based on conditions within a function

I am currently working with an object that contains orders from a restaurant. var obj = { orders: [ null, { date: "2018-07-09 10:07:18", orderVerified : true, item: [ { name ...

Creating a custom variable assignment in Bootstrap within the custom.scss file

I've been searching for a solution to this problem for half a day now. My goal is to change the value of the $primary variable from the default $blue to the $orange variable. I tried following the instructions in the documentation: $primary: red; @imp ...

Detecting the clicked tab in Ajax Control Toolkit TabContainer - is it possible to determine which tab was selected?

I need some help with the TabContainer component from the Ajax Control Toolkit. My goal is to detect which specific tab a user has clicked on (such as by its index). If anyone has any insights on how to achieve this, please let me know! ...

Tips for positioning bootstrap dropdowns side by side in a row

I'm having trouble aligning my li items in a Bootstrap dropdown next to each other. I've tried everything but nothing seems to work. Here's my code: <nav class="navbar navbar-expand-lg navbar-light bg-light"> < ...

What steps are needed to have AJAX retrieve data from the controller within an MVC framework?

So, I am struggling with making an AJAX call in my project. I need to return a string as a JSON object from the controller back to the view where the ajax call is made. Despite numerous attempts, I have been unable to achieve this successfully. My main que ...

Vue3: Pinia store data not being received

Having trouble retrieving Pinia data using the Composition API after a page reload? I'm utilizing Vue to parse fetched JSON data. Despite being new to the Composition API, I can't pinpoint what's causing the issue even after going through th ...

Express displays HTML code as plain text

I am currently facing an issue where I am trying to display an html table on /guestbook.ejs and then redirect it to /guestbook. However, the content of my guestbook.ejs file is being displayed as plain text rather than rendering the HTML code. Below is th ...

Using $stateParams injection for unit testing Angular applications with Karma

Here is the starting point for the controller code: angular .module('hc.hotelContent') .controller('NameLocationController', nameLocationCtrlFn); //Todo change hotelDataService nameLocationCtrlFn.$inject = ['$stateParams', &a ...

Is there a way to pre-load images from component B within component A using Vue?

In a scenario where I have two Vue files, A.vue and B.vue, the issue arises when navigating from A to B. B contains numerous images fetched from Firebase realtime database, resulting in slow loading times upon first visit. To address this, I aim to preload ...

Material Design Angular2 Toolbar

I am currently working on designing a toolbar using Material and Angular2. My main challenge is formatting the toolbar in such a way that the search bar appears centered in white, while the "Create Project" button and other buttons are aligned to the right ...

What steps do I need to take to implement AJAX form authentication?

I have set up a login screen that validates username and password credentials through a php script. When a user enters their information and submits the form, the authenticate.php file executes an LDAP bind. If the credentials are correct, the user is redi ...

The issue of Angular 2.3.1 custom validator promise not resolving

I am currently working on implementing a sign up form in which I need to check if the username is already taken or not. To accomplish this, I have decided to use promises. The structure of my sign-up component is as follows: import { Component, OnInit } f ...

Why isn't my ajax call working after using window.close?

Whenever I click the button on my page, a small window opens and the value from the window is sent to my controller before closing. However, I noticed that when I include the window.close() line, the controller does not get hit. It works perfectly fine wit ...

` `Spinning graphics and written content``

I am looking to create a dynamic element on my website where an image and corresponding text block rotate every few seconds. An example of what I am envisioning can be seen on this website: While I know how to implement a javascript for rotating images, I ...

Inheriting the viewBox attribute with SvgIcon

I have a collection of unique custom SVGs, each with its own distinct viewBox. First Custom SVG <svg viewBox="-4 -4 24 24"><path something/></svg> Second Custom SVG <svg viewBox="-5 -7 24 24"><path something ...

Recognizing the click event on the checkbox within a <TableRow/> in ReactJS with MaterialUI

Using ReactJS and MaterialUI's component for tables, I have successfully created a table with two rows, each containing a checkbox. Now, the challenge is to create a method that can recognize when a checkbox is clicked and provide information about th ...

Utilizing class-validator for conditional validation failure

Implementing conditional validation in the class-validator library using the given example, I need to ensure that validation fails if the woodScrews property is assigned a value when the tool property is set to Tool.TapeMeasure. I've searched extensiv ...

Utilizing Loopback Callbacks within a Looping Structure

While working in a for-loop, I encountered an issue where I needed to access the loop variable 'i' from within a callback function but it was not accessible due to closure restrictions. Despite attempting different methods such as using (i) or ca ...

Attempting to trigger a second modal confirmation from within a modal confirmation

I've been struggling to solve a problem and I haven't had any luck. Can someone please help me? Here is the desired outcome: I already have a modal dialog that pops up. It contains two buttons: Ok and Cancel. When I click on the Ok button, it ...