Search code examples
phpajaxsocial-networking

Getting each foreach loop in ajax


I'm currently looking at making a social media style site.

I have a foreach displaying a sql table of user posts.

I've looked and found how to submit to a php file without refreshing but now I'm in need of a way to have the ability to like each individual post.

Currently, if I put the ajax script at say the bottom, it likes the last post within the foreach loop. Any suggestions on how I can have it "like" the correct post? Hopefully this explains enough.

My ajax code:

$(document).ready(function(e){
    e.preventDefault();
    $.ajax({
        url: "get_data.php",
        type: "POST",
        data: {postid, $postid},
        success: function(data){
            
    });
});

Solution

  • You can for example have a button for every post and you add onclick event that call the function and passing the post id as function parameters.

    So your function will look like something

    function likePost(postid){
      try{
        
          $.ajax({
            type: "POST", 
            url: "get_data.php",
            data:{"postid": postid},
            success: function(data){
                 console.log(data);       
        }
          });
    
     
      }
      catch(e){
        alert(e);
      }
    }