0

I'm trying to get post id and insert it into database after user click on add to favorite button.

The problem that all the post are return id 30 which is the last id in the database.

My php/html code

while($row = mysqli_fetch_array($get_posts)) {
    <i style="float:right;" class="fa fa-pinterest-square">
       <form id="pin_post" method="post"> ';
          if (isset($_SESSION['user_id'])){
               <input type="hidden" value="'. $_SESSION['user_id'].'" name="user_id" /> 
            }

            <input type="hidden" value="'.$row['post_id'].'" name="post_id[]" />

        </form>
     </i>

The jQuery / Ajax code

<script>

    $(document).on("click",".fa-pinterest-square",function(e) {


        $.ajax({
            url: "includes/test.php",
            type: "POST",
            data: $('#pin_post').serialize(),
            success: function(data) {
                alert(data);
            }
        });

    });
</script>

I'm getting last id in the database when I click any post.

Please help me to get the id of each post when I click on the

2
  • so should I put the form out the loop or what? Commented May 23, 2016 at 1:42
  • you should be getting parse errors here. while($row = mysqli_fetch_array($get_posts)) { <i style="float:right;" class="fa fa-pinterest-square">...</i> Commented May 23, 2016 at 1:44

1 Answer 1

1

Since you are using #pin_post when serializing it you will get the last hit when jQuery is looking for #pin_post. Either you should use a unique id or something like this

$(document).on("click",".fa-pinterest-square",function(e) {
    var form = $(this).find('form'); //Since the form is child to <i>
    $.ajax({
        url: "includes/test.php",
        type: "POST",
        data: form.serialize(),
        success: function(data) {
            alert(data);
        }
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much it worked like a charm. Can you explain how var form = $(this).find('form'); get the id for each post coming from the data base.
That is because when you are trying to access #pin_post you have to be sure of that the <element id="pin_post"> is unique (not existing elsewhere in the HTML), the id attribute always has to be unique! What I did was based on the the click event, accessed its children, in this case the <form> that you want to serialize. (Do mark the comment as correct)
Thank you very much. Sure I will do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.