Leveraging the power of Ajax to dynamically submit a single form nested within a forEach iteration

I'm currently working on a database query that retrieves all user posts. This query is then used in a forEach loop to generate a post for each result:

for($indexPost=0; $indexPost < $postCount; $indexPost++) {

//Code for handling the post

echo<<<_END

<form action="feedLikes.php" id="likePostForm" method="post">

<input type="hidden" name="feedIDForLike" class="feedIDForLike" value="$feedID">

<button type="submit" class="likeButton"></button>

</form>

_END;

}

All post information is correctly displayed when loaded. However, I am facing an issue with the like button functionality. When the like button is clicked, it triggers an ajax call:

$(document).ready(function()
{

 $('#likePostForm').on('submit', function (e) {  
    e.preventDefault();
    likePost();
 });

});

function likePost()
{  
var feedIDLike = $(".feedIDForLike").val();



     $.ajax({
      url: "feedLikesClicked.php",
      cache: false,
        type: "POST",
         data: {feedIDLike: feedIDLike},
         dataType: "html",
      success: function(html){
          location.reload();
      }
    });
    }

This implementation works, but there's a problem - when I click the like button on a post, the entry gets duplicated in the database for every post on the feed. The issue seems to be that the ajax call is triggered by all posts rather than just the one I clicked on.

So my question is, how can I modify the ajax function to run only for the individual form that was clicked, especially considering the forms were created in a loop?

Any help or suggestions would be greatly appreciated.

Attempts So Far

As each form ID needs to be unique, I tried changing the form line to:

<form action="feedLikes.php" id="likePostForm$feedID" method="post">

And then updated the jQuery line at the top to:

var feedID = $(".feedIDForLike").val();

$('#likePostForm'+ feedID).on('submit', function (e) {  
    e.preventDefault();
    likePost();
 });

Unfortunately, this approach yielded the same results.

Answer №1

To differentiate between forms, I included a data attribute within each form so that they each have their own unique identifier. By utilizing an onsubmit function in your code, you can easily pass the selected form using `this` to the `likePost` function. From there, extracting the specific data-feedID from the passed element becomes straightforward. The issue with the existing code lies in the fact that it was targeting every element with the class `feedIDForLike`.

<?
for($indexPost=0; $indexPost < $postCount; $indexPost++) {

    //All information related to the post
    echo<<<_END
        <form action="feedLikes.php" id="likePostForm" data-feedID="{$feedID}" method="post">
            <button type="submit" class="likeButton"></button>
        </form>
_END;

}

?>

<script>
    $(document).ready(function() {

        $('#likePostForm').on('submit', function(e) {
            e.preventDefault();
            likePost(this);
        });

    });

    function likePost(elem) {
        var feedIDLike = elem.attr("data-feedID");
        $.ajax({
            url: "feedLikesClicked.php",
            cache: false,
            type: "POST",
            data: {
                feedIDLike: feedIDLike
            },
            dataType: "html",
            success: function(html) {
                location.reload();
            }
        });
    }
</script>

Answer №2

Make sure to rearrange your code by moving the likePost() function inside the submit function and utilize jquery's this and closest methods to retrieve the variable.

$(document).ready(function()
{

 $('#likePostForm').on('submit', function (e) {  
    e.preventDefault();

    //adjust your code similar to this
    var feedIDLike = $(this).closest( ".feedIDForLike" ).val();

    $.ajax({
      url: "feedLikesClicked.php",
      cache: false,
        type: "POST",
         data: {feedIDLike: feedIDLike},
         dataType: "html",
      success: function(html){
          location.reload();
      }
    });
 });

});

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

PHP - unique regular expression features

Here is a string that I have: var wcall=wicketAjaxGet('?x=-DxRtr1ApWy1S-JoAgFwCid5mDvsjhWOhXpq0nZdO*WsUggdTvpUtQ',function() { }.bind(this),function() { }.bind(this), function() { I am trying to extract this part from the string: ?x=-DxRtr1ApW ...

Do you think my approach is foolproof against XSS attacks?

My website has a chat feature and I am wondering if it is protected against XSS attacks. Here is how my method works: To display incoming messages from an AJAX request, I utilize the following jQuery code: $("#message").prepend(req.msg); Although I am a ...

Can a Spring MVC controller method return a JSONArray using @ResponseBody annotation?

I am facing an issue with AJAX while trying to load a URL that should return data from my controller in JSONArray format. However, when the call is made, I encounter a 406 not acceptable error. Is there any way to resolve this using @ResponseBody? Despite ...

Modify the color scheme of an HTML webpage

Looking to enhance my HTML page with a new feature. The page is responsive and currently using Bootstrap CSS and JS. My goal is to allow users to change the color of the page dynamically by selecting a background or text color. Check out this example link ...

Creating a dynamic grid in ExtJS 4 that changes based on the selection made in a combobox

Currently, I am utilizing a grid with remote store and pagination due to the sheer volume of records present. The main grid's store is set up as follows: Ext.define('ArD.store.RecordsListStore', { extend: 'Ext.data.Store', ...

The jQuery Deferred feature on Ajax is failing to properly pass the array in the data option as an array, instead converting

I am facing an issue in my application where I want to use jQuery deferred to handle Ajax success and error uniformly from a central location. It works perfectly fine when I pass strings in the data option, but when I try to pass an array, it gets sent as ...

Is there a way to smoothly navigate back to the top of the page after the fragment identifier causes the page to scroll down?

I do not want to disable the functionality of the fragment identifier. My goal is for the page to automatically scroll back to the top after navigating to a specific section. This inquiry pertains to utilizing jQuery's UI tabs. It is crucial to have ...

Convert your HTML document into a Microsoft Word file and see the total number of pages in

I have been experimenting with creating a Word document using HTML code. Thanks to various examples, I have made some progress. However, I am facing an issue where I cannot get the total number of pages to display as text on the first page of the document. ...

Switch from using a curl query to making an ajax query with mootools

My current approach involves using curl to fetch json data from nuxeo. Below is the function I am currently using: curl -X POST -H "Content-Type:application/json+nxrequest" -d "{ params: { query:'SELECT * FROM Document' ...

The importance of managing session data

Here is my issue: I want only one session to run at a time. Consider the following query: $get_crs_mysqli .= (!empty($_SESSION['userSearch']))?(" AND (course_title like '%".$_SESSION['userSearch']."%') OR (course_title like & ...

Need some assistance with Javascript Ajax? Specifically, dealing with multiple values?

My goal is to asynchronously post an array of messages using this code. Despite my efforts, I've encountered a challenge where it doesn't only post the four items in the array but also adds gibberish text. Additionally, there seems to be an issue ...

How can I make my image shine when the mouse hovers over

I have recently come across a fascinating effect where an image glows up when the mouse hovers over it. This is not your typical border glow, but rather a unique enhancement of colors within the image itself. I discovered a library called Pixastic that can ...

Pressing the "Enter" key will submit the contents of

Hello, I have recently created a new chat box and everything seems to be working fine. However, I am facing an issue with submitting a message when I press enter (to go to the function Kucaj()). Can anyone provide assistance with this problem? I tried ad ...

The networking feature stops functioning on Android devices after upgrading from Ionic 1.5.0 to 1.6.3

After upgrading from ionic 1.5.0 to 1.6.3 (the latest version), I noticed that networking ajax calls were no longer working on Android. I had to remove and re-add the android platform, and there seemed to be a change in the apk names from MainActivity-debu ...

Using PrimeFaces selectors to update a non-JSF component with Ajax

Can Primefaces selectors - PFS be used to update any html fragment? Take a look at this scenario: <h:outputText id="test" value="#{testBean.date}"/> <span id="test2"><h:outputText value="#{testBean.date}"/></span> <p:commandBut ...

The functionality of the jQuery program is compromised when used on the Google Chrome browser

I just recently started diving into the world of Jquery, attempting to learn it from scratch. However, I have encountered an issue while trying to make my Jquery program run smoothly: Let's take a look at the CSS first: p { opacity: 0; } Now on ...

Send binary information using Prototype Ajax request

Currently, I am utilizing Prototype to send a POST request, and within the postdata are numerous fields. One of these fields contains binary data from a file, such as an Excel spreadsheet chosen by the user for upload. To retrieve the contents of the file ...

What is the best way to ensure the search box remains fixed in the top navigation bar while maintaining a fluid and responsive design?

I've been struggling as a novice programmer, and even with the help of more experienced programmers, we haven't been able to figure it out. I'm trying to integrate a search box into the top navigation that adjusts responsively to different ...

What is the best way to unselect the "all" selector if one of the inputs is no longer selected?

I am facing an issue with a search filter functionality. When all filters are selected and then deselected individually or together, the "all" button remains selected. I need help in ensuring that when any filter is deselected, the "all" button also gets d ...

Exploring the DOM with jQuery to effectively select multiple elements

I am currently attempting to locate and select all elements with the "findme" class, and then identify the selects that are located nearby. http://jsfiddle.net/R93md/1/ Specifically, I have experimented with $(".findme").parent().prev().first(); Once ...