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

Styling in Svelte/TS does not change when applied through a foreach loop

I've been experimenting with creating a unique "bubble" effect on one of my websites, but I'm facing difficulty changing the styling in a foreach loop. Despite no errors showing up in the console, I'm at a loss as to how to effectively debu ...

make sure the <option> tags fit seamlessly inside a Bootstrap card

I'm currently working on a project using Angular in combination with Bootstrap 4.0. My goal is to integrate <select>, <option>, and <optgroup> elements within a card. Below is the code snippet from the component.html file: <div ...

Can you explain the {| ... |} syntax in JavaScript to me?

While reviewing a javascript codebase, I stumbled upon a section of code that appears as follows: export type RouteReducerProps = {| error?: Error, isResolving: boolean, isResolved: boolean, hasFailed: boolean, |}; Upon closer inspection, it seem ...

What is the best way to use jQuery to position a <div> at the bottom of another <div>?

Is there a way to achieve something similar to this concept? The dimensions displayed are just for visualization purposes, but feel free to utilize them. I am interested in moving the smaller red <div> box and attaching it to the bottom of the larg ...

Using Ajax to Filter Table Data in Codeignitor

I'm facing an issue with filtering table data using Ajax. The desired functionality is that when I select BANK CREDIT from the drop-down menu, it should retrieve employee details where the modeofpay (a column in the table) is "BANK CREDIT". Similarly, ...

tips for getting two ajax json Data from .net

When working with .NET, I am encountering an issue where I need to send two sets of JSON data (test1 and test2) to a .NET controller using JavaScript (ajax). Here is the code snippet for sending the data: .ajax({ type: 'POST', url ...

Arrange a div beneath another div that is positioned absolutely

Within my code, I have a div with the property of absolute positioning referred to as "abs". Right after this div, there is another div called "footer" which does not have any specified position value assigned to it. Even though I've experimented with ...

How can one create a hidden color box?

$.colorbox({ href:"/check.html", transition:"elastic", speed: 150, innerWidth:"910", iframe:true, fastIframe:false, fixedPosition:fixedPos, onComplete:function(){ var $ ...

Utilize a fluid AJAX endpoint for the Vue Select2 encapsulated component

I have customized the Wrapper Component Example based on VueJS documentation by adding the AJAX data source feature. You can view my modified code here. My goal is to dynamically set the ajax url property of my select2 component, like this: <select2 :o ...

Tips for submitting a form remotely using Radix Alert Dialog and the form attribute

Currently, I have integrated a Radix UI's Alert Dialog in my Next.js 13 app to confirm the deletion of a contact from the user's contact list: Take a look at the Alert Dialog modal here However, there seems to be an issue with the delete button ...

Retrieve particular data points from the object based on its unique identifier

Hey there, I'm facing an issue with Angular where I need to retrieve a specific object from an array based on its ID. I'm quite lost on how to approach solving this problem. var Obj = [ { Id: "1", shape: "circle", color: "red" }, { Id: " ...

Enhance autocomplete functionality in jQuery with the ability to search for specific

Whenever a user types into an input field, I need to display a list of arrays. To achieve this, I've utilized the jQuery autocomplete plugin successfully. However, I'm facing difficulty in adding the search text as a new option in the autocomplet ...

python extract values from a JSON object

I've been searching everywhere, but I haven't been able to find a solution. It seems like my question is not clear enough, so I'm hoping to receive some guidance. Currently, I am working with turbogears2.2. In my client view, I am sending a ...

The metallic material in Substance Painter appears as a dark shade in A-Frame

After exporting an object as gltf from Substance Painter, I am importing it into my A-frame scene. Strangely, the metallic outer material appears dark in my current scene while other materials like plastic appear white and are visible. Despite already ha ...

Populating fields in a new AngularJS document from a table

I have a project where there is a table displaying different instances of our service, and each row has an info button that opens a form with the corresponding row's information autofilled. However, I am facing an issue where by the time I retrieve th ...

Incorporate a JavaScript variable within the src attribute of a script tag

Embedding Google's script allows for displaying a trends Map on our website. <script type="text/javascript" src="//www.google.com.pk/trends/embed.js?hl=en-US&q=iphone&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&a ...

Isn't AJAX all about the same origin policy?

Despite my confusion surrounding the same domain origin policy and jQuery AJAX, I have noticed that when I make a GET request to a URL using jQuery, I am able to successfully retrieve the results. This goes against what I understood about the restriction ...

Update the input value to replace duplicate values in the Chrome Android 6x version

Recently, I encountered an issue with my Samsung Galaxy Note 4. I have been working with jQuery and attempting to write code that will automatically format input text into a specific pattern when a person fills in a value (using keyup event). For examp ...

Incorporate videos from platforms like Youtube, Vimeo, and more

I am looking to add videos to my website without hosting them on my server. I want the flexibility to use links from any source, not just YouTube or Vimeo. Is there a way to achieve this using something similar to an iframe? <iframe width="560" heigh ...

What is the best way to customize the lower border color of a collapsed Bootstrap navbar with an inverse design

Discussing this issue.. I am noticing two distinct colors. One is darker than the background shade and the other is lighter than the background shade. How can these be set? <nav class="navbar navbar-inverse"> <div class="container-fluid"> ...