Invoke data-id when the ajax call is successful

Initially, there was a smoothly working "like button" with the following appearance:

<a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span></a>

Below is the Ajax code snippet:

<script>
    $(function(){
        $(".like").click(function(){

            var postid = $(this).attr("id");
              $.ajax({
                type:'POST',
                url:'addlike.php',
                data:'id='+postid,
                success:function(data){
                   if(data=="you already liked this post"){
                       alert(data);
                     }
                   else{
                      $('a#'+postid).html(data);
                      }
                }
            });

        });
    });

</script>

Upon successful AJAX request, addlike.php will return two possible responses - an alert saying "you already liked this post" if the user had already liked it, or the updated number of likes. For instance, if there were 10 likes and the user clicks the button, $('a#'+postid).html(data) would update the count to 11, where 'data' represents the new like count, and $('a#'+postid) selects the clicked "like button".

Due to certain requirements, I need to use data-id instead of id for the button's HTML id attribute. More details can be found here.

Now, post a successful AJAX response, how can I target the element with a data-id instead of id? I attempted the following methods:

     $('a#data-id'+postid).html(data);
     $('.[data-id="postid"]').html(data);
     $('a[data-id='+postid']').html(data);
     $('a#'+"[data-id=postid"]).text(data);

Unfortunately, none of these approaches seems to work. Any help will be greatly appreciated.

Answer №1

Choose an item using the data attribute:

$('a[data-id="'+postid +'"]').html(data);

Answer №2

Ensure that you add a data-id attribute to your anchor tag, similar to how you have an id property. Once added, it should function as expected.

Answer №3

When using the variable post-id, be sure to enclose it in quotes ("") or single quotes ('') since it can contain any characters. This rule applies to all attributes except for ID and CLASS, as outlined in the jQuery documentation.

$("a[data-id='" + postid + "']").html(data);

Answer №4

If you already have a reference to the button in $(this) within the click handler, it's recommended to save that into a variable and use it like this:

<script>
    $(function(){
        $(".like").click(function(){
            var $linkClicked = $(this);
            var postid = $(this).attr("id");
              $.ajax({
                type:'POST',
                url:'addlike.php',
                data:'id='+postid,
                success:function(data){
                   if(data=="you already liked this post"){
                       alert(data);
                     }
                   else{
                      $linkClicked.html(data);
                      }
                }
            });

        });
    });

</script>

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

Suggestions for resolving the "Undefined" problem in my JQuery Ajax web service request

Below is the JavaScript code I've written: function testService(test) { var data = "{param2:\"" + test + "\"}"; $.ajax({ type: "POST", url: "WebService1.asmx/HelloWorld", dataType: "json", data: data, contentType: "appli ...

Tips for Identifying Different ID Values of HTML Elements with jQuery

Currently, I have two different divs on my webpage, each containing buttons and hidden fields. When I try to pass the value of the hidden field attached to the button in a jQuery function, I encounter an issue where clicking on the second div results in pa ...

The tooltip popup does not appear within the nz-tabs

Looking to enhance my two tabs with an info icon preceding the tab text, along with a tooltip popup that appears when hovering over the icon. Despite trying different methods, I have yet to achieve the desired outcome. <nz-tabset [nzLinkRouter]=&qu ...

Enhancing Website Performance with Vue.js 2.0 Lazy Loading

I'm attempting to implement Lazy Loading for my components in Vue.js 2.0 (within a Laravel 5.3 project). As per the guidelines, I should proceed like this: Vue.use(VueRouter); const Forum = resolve => require(['./Components/Forum/Forum.vue& ...

Manipulating the DOM within an Angular application

What is the best way to perform DOM manipulation in Angular without using jQuery? Here is an example of code using jQuery: $(".next-step").click(function (e) { var $active = $('.wizard .nav-tabs li.active'); $active.next().removeClass(& ...

Tips for iterating through nested objects with a for loop

Struggling with validations in an Angular 5 application? If you have a form with name, email, gender, and address grouped under city, state, country using FormGroupname, you might find this code snippet helpful: export class RegistrationComponent implemen ...

Obtain text content using JQuery and AJAX rather than retrieving the value

I am struggling with a dynamic table that needs to perform calculations before submitting, requiring the presence of values. However, I want to submit the text from the options instead of the values. Despite trying various approaches, none of them seem to ...

What is the typical output value that fluctuates?

I only have one input to work with. My goal is to set the input value to "5", then display "3" in the "total" field and "4" in the "total2" field. Additionally, for every increment of +1 to the input value, I want the "total" and "total2" fields to also in ...

The wrap() method in jQuery clones elements multiple times

I have created a simple function that wraps a div tag inside another div tag when the browser window exceeds a certain width of x pixels. However, I've encountered a strange bug when resizing the page more than once. Let me share with you the jQuery ...

Techniques, modules and functions in Javascript

How should I properly document this code snippet: // Define a collection of colors with methods colors = { // Define method for color red "red" : function() { // Do something... } // Define object for color black "black" : { // Add ...

Combining two objects in AngularJS to create a new merged object

Is there a way to merge object1 and object2 into object3, updating values corresponding to matching keys while ignoring unmatching keys? var object1 = { "pii" : "val1", "loc" : "val2" } var object2 = { "rrb" : "val3", "voc" : "val4" } var obje ...

Leveraging WebApi for ADFS authentication

We are currently working on setting up the following scenario: An HTML page sends an AJAX request to a WebApi inquiring about whether or not a user has a specific role. The WebApi then checks with ADFS to see if the user is logged in (if not, it authentic ...

Transforming an Axios image stream into a string by encoding it with Base64?

Currently, this is what I have in place: const Fs = require('fs') const Path = require('path') const Axios = require('axios') var {Base64Encode} = require('base64-stream'); const url = 'https://unsplash.co ...

Arranging elements within an outer array by the contents of their inner arrays

I need help organizing an array based on the alphabetical order of a specific value within the inner arrays. For example: I want to sort this array by the prefix "old," so old A, old B, etc. const array = [ { personName: "Vans", personTags: ["young", " ...

Error: $this.text is throwing a TypeError and is not working as a function

Upon examining the code below: var $this = $(this).children('div.submenu1').children('a.subtile')[0], title = $this.text(), name = $this.attr('node').val; An error is encountered: Uncaught TypeError: $this.text is not a fun ...

What is the best way to bring an image into your nextjs project?

I have a question about importing images into my Next.js project. I created an array of objects and want to import an image stored in a folder on my laptop, specifically in the src folder rather than the public folder. How can I properly achieve this in ...

Despite initializing session_start(), the session variable remains unchanged and fails to update

I have a page called train_detail.php. The table on this page was created using SQL and includes the column attribute train_id. Each row in the table has a button named check_availability. When this button is clicked, it opens a new modal that passes the v ...

Ending or stopping based on data retrieved from an ajax call

Currently, I have a php script that includes an image which, upon clicking, redirects the user to a different page. Additionally, there is an ajax/jQuery function in place to check if the user is logged in or not. When the user clicks on the link, the aja ...

Looking to crop a canvas without changing its dimensions using jQuery

I'm currently working on a project that involves overlaying two images; one uploaded by the user and the other a default image. However, I am facing an issue when the uploaded image is a rectangle instead of a square, causing the canvas to resize it. ...

Automated scrolling within a div when an li element overflows

Looking to implement automatic scrolling in a div. I have a list of elements within a fixed height div, and now I want the div to scroll automatically when I press the down key after highlighting the 3rd li element (i.e Compt0005). Can anyone help me solve ...