2

i have a feed page which loads posts (known as 'shouts' in my code) from a database based on who the user is following ('scouting' in my code). The basic information is displayed correctly. However, in each post i would like to load a separate file using ajax which will control the likes of the post. Below is my PHP for the feed page:

$findShouts = $pdo->prepare('SELECT * FROM feed WHERE name IN (SELECT scouting FROM scout WHERE scouted =? OR scouting =?)  ORDER BY timestamp DESC');

//execute query and variables
$findShouts->execute([$username, $username]);


if ($findShouts->rowCount() > 0)
    {    

//get the shouts for each scout
while($row = $findShouts->fetch(PDO::FETCH_ASSOC)){ 

$shoutID[]              = $row['id'];
$shoutUsername[]        = $row["username"];
$shoutName[]            = $row["name"];
$shoutText[]            = $row["text"]; 
$shoutTimestamp[]       = $row["timestamp"];  
} 


$shoutCount = count($shoutUsername); 


for($indexShout=0; $indexShout < $shoutCount; $indexShout++) {        


print'
<div class=feedNewShout>

<div class=shoutInformation>

<div class=shoutName>
<p>'. $shoutName[$indexShout] .'</p>
</div>

<div class=shoutTimestamp>
<p>'. timeElapsed("$shoutTimestamp[$indexShout]", 2) .'</p>
</div>

<div class=shoutText>
<p>'. $shoutText[$indexShout] .'</p>
</div>

<input type="hidden" name="feedID" class="feedID" value="'. $shoutID[$indexShout] .'">

<div class=likesAjax>
</div>    


</div>
</div>';

}
unset($shoutID);
unset($shoutUsername);
unset($shoutName);
unset($shoutText);
unset($shoutTimestamp);
} 

In each post the div class=likesAjax performs an ajax call which sends the hidden $feedID to feedlikes.php.

feedLikes.js

$(document).ready(function()
{

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

 $.ajax({
  url: "feedLikes.php",
  cache: false,
    type: "POST",
     data: {feedID: feedID},
     dataType: "html",
  success: function(html){
    $(".likesAjax").empty();  
    $(".likesAjax").append(html);
  }
});

    });

feedLikes.php

if (isset($_POST['feedID']))

    {

 $feedID = ($_POST['feedID']);  

echo "$feedID";
}

the problem i have is that i can see the ajax goes through every post and echos the feedID, however, every time a new call is made, all the feedID's change to the same thing. I know this is because my success call in my ajax updates every likesAjax class to the same thing. So whatever the feedID is of the last post, will be displayed for all of them.

My question is, how can i load feedLikes.php so that every post is shown with its own $feedID?

Note, feedLikes.php will eventually do something with the ID, the echo is just for test purposes.

4
  • Select all the feed items, loop over them (.each), and then inside access the current item using $(this) Commented Jul 12, 2017 at 13:02
  • You could loop through your likesAjax with a jquery each loop like $(".likesAjax").each(function() {var feedID = $(this).attr("data-id") }); and after the feed id execute your ajax call to update each one. You could wrap your call in a new function that expects a parameter feedid to call it more easily. The optimal thing imo would be to create a call that brings all items and loop through it and update thr values once, in the calls result. Commented Jul 12, 2017 at 14:59
  • @StavrosAngelis your below answer combined with the new jquery you mentioned in the comment above has worked perfectly thankyou! i did as the first answer below and changed my jquery file to go through every each loop like above. If you want to edit the below answer with the addition to the first thing described in the above comment i will accept it. Commented Jul 12, 2017 at 15:32
  • hehe, I answered from my mobile and clicked on the wrong place to add my comment. Commented Jul 12, 2017 at 16:15

1 Answer 1

2

Without changing your codes' logic, in PHP you can add an attribute to each ".likesAjax" box called data-id:

<div class="likesAjax" data-id="'.$shoutID[$indexShout] .'">

Now in jQuery in your ajax success function you can update your selector to look for this attribute as well in order to update the correct ".likesAjax" element:

$(".likesAjax[data-id='"+ feedID +"']").append(html);

To put these all together you would need to loop through your .likesAjax elements. To make your code a little cleaner you should make a function with the feedID as a parameter that will be executed for every step of the loop. This will look like the following:

$(".likesAjax").each(function() {
    var feedID = $(this).attr("data-id");
    loadFeedLikes(feedID);
});

function loadFeedLikes(feedID) {
    $.ajax({
      url: "feedLikes.php",
      cache: false,
      type: "POST",
      data: {feedID: feedID},
      dataType: "html",
      success: function(html){
         $(".likesAjax[data-id='"+ feedID +"']").html(html);
      }
    });
}

If you want to make this lighter you can create a new feedLikes.php that takes all the feedLikes you have and pushes them in an array. This array should contain the content you need and the feedId. Then you would only need one ajax call and with a for loop you could loop through the results and update all the $(".likesAjax") elements at once. This way you will have only one query to your db and only one ajax call to fetch your data.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.