0

I have a form within a while-loop and am using javascript/ajax to make the db edits and post a success message. The only issue I have is with the success message. Since the Id is being repeated the success message displays beneath the first record returned, instead of beneath the record the user selected. How can I assign a unique Id to resolve this?

    <div id="content-new">
    <?php   
    $sql_action = "SELECT movies.img, movies.title, movies.title_full, movies.new, my_list.title, my_list.username FROM movies LEFT JOIN my_list ON movies.title_full = my_list.title WHERE new != '' ORDER BY movies.id DESC LIMIT 16";
    $result_action = mysqli_query( $db_connect, $sql_action )or die( mysqli_error( $db_connect ) );
    while ( $row_action = mysqli_fetch_assoc( $result_action ) ) {
      $img = $row_action[ 'img' ];
      $title = $row_action[ 'title' ];
      $title_full = $row_action[ 'title_full' ];
      $new = $row_action [ 'new' ];
      $mylist = $row_action[ 'username' ];
        
      // CHECK IF FAV EXISTS MORE THAN ONCE IN DB
      $stmt_count_fav = $db_connect->prepare("SELECT title FROM my_list WHERE title = ?"); 
      $stmt_count_fav->bind_param("s", $title_full);
      $stmt_count_fav -> execute();
      $stmt_count_fav -> store_result();
      $stmt_count_fav -> fetch();
      $count_fav = $stmt_count_fav->num_rows;
      $stmt_count_fav->close();
      ?>
    
<div id="div_fav_hover" style="display: inline-block;">
<?php if ( $mylist != "") { // ON MY LIST ?>
<div id="id_new_delete" style="display: inline-block;">
    <form id="form-new" style="display: inline-block;" class="class_new_delete">
        <input style="display: none" type="text" name="title_home" value="<?php echo $title_full; ?>" />
        <input style="display: none" name="favorite_delete_home" value="favorite_delete_home" />
        <input id="btn_mylist_on_home" style="margin-bottom: 10px; margin-left: -135px;" type="submit" name="btn_password" value="" class="class_fav_hover_on">
    </form>
</div>
<?php } else { // NOT ON MY LIST OR ANOTHERS ?>
<div id="id_new_add" style="display: inline-block;">
    <form id="form-new" style="display: inline-block;" class="class_new_add">
        <input style="display: none" type="text" name="title_home" value="<?php echo $title_full; ?>" />
        <input style="display: none" name="favorite_home" value="favorite_home" />
        <input id="btn_mylist_default_home" style="margin-bottom: 10px; margin-left: -135px;" type="submit" name="btn_password" value="" class="class_fav_hover_off">
    </form>
</div>
<?php } ?>
</div>

<?php } // END LOOP ?>
        
            <script>
                $(function () {
                  $('.class_new_add').submit('click', function (event) {
                    event.preventDefault();
                      $.ajax({
                        type: 'POST',
                        url: 'ajax/mylist.php',
                        data: $(this).serialize(),
                        success: function (data) {
                          $('#id_new_add').html("Added to My List");
                        }
                      });
                    });
                  });
                $(function () {
                  $('.class_new_delete').submit('click', function (event) {
                    event.preventDefault();
                      $.ajax({
                        type: 'POST',
                        url: 'ajax/mylist.php',
                        data: $(this).serialize(),
                        success: function (data) {
                          $('#id_new_delete').html("Removed from My List");
                        }
                      });
                    });
                  });
            </script>
    </div>

Here's an update. Please excuse my ignorance with JavaScript... Right now the success isn't displaying at all.

    <div id="content-new">
    <?php   
    $sql_action = "SELECT movies.img, movies.title, movies.title_full, movies.new, my_list.title, my_list.username FROM movies LEFT JOIN my_list ON movies.title_full = my_list.title WHERE new != '' ORDER BY movies.id DESC LIMIT 16";
    $result_action = mysqli_query( $db_connect, $sql_action )or die( mysqli_error( $db_connect ) );
    while ( $row_action = mysqli_fetch_assoc( $result_action ) ) {
      $img = $row_action[ 'img' ];
      $title = $row_action[ 'title' ];
      $title_full = $row_action[ 'title_full' ];
      $new = $row_action [ 'new' ];
      $mylist = $row_action[ 'username' ];
        
      // CHECK IF FAV EXISTS MORE THAN ONCE IN DB
      $stmt_count_fav = $db_connect->prepare("SELECT title FROM my_list WHERE title = ?"); 
      $stmt_count_fav->bind_param("s", $title_full);
      $stmt_count_fav -> execute();
      $stmt_count_fav -> store_result();
      $stmt_count_fav -> fetch();
      $count_fav = $stmt_count_fav->num_rows;
      $stmt_count_fav->close();
      ?>
    
<div id="div_fav_hover" style="display: inline-block;">
<?php if ( $mylist == $username) { // IS A FAVORITE ?>
<div class="div_new_delete" style="display: inline-block;">
    <form id="form-new" style="display: inline-block;" class="class_new_delete">
        <input style="display: none" type="text" name="title_home" value="<?php echo $title_full; ?>" />
        <input style="display: none" name="favorite_delete_home" value="favorite_delete_home" />
        <input id="btn_mylist_on_home" style="margin-bottom: 10px; margin-left: -135px;" type="submit" name="btn_password" value="" class="class_fav_hover_on">
    </form>
</div>
<?php } else { // NOT A FAVORITE ?>
<div class="div_new_add" style="display: inline-block;">
    <form id="form-new" style="display: inline-block;" class="class_new_add">
        <input style="display: none" type="text" name="title_home" value="<?php echo $title_full; ?>" />
        <input style="display: none" name="favorite_home" value="favorite_home" />
        <input id="btn_mylist_default_home" style="margin-bottom: 10px; margin-left: -135px;" type="submit" name="btn_password" value="" class="class_fav_hover_off">
    </form>
</div>
<?php } ?>
</div>

<?php } // END LOOP ?>
        
            <script>
                $(function () {
                  $('.class_new_add').submit('click', function (event) {
                    let thisform = this;
                    event.preventDefault();
                      $.ajax({
                        type: 'POST',
                        url: 'ajax/mylist.php',
                        data: $(this).serialize(),
                        success: function (data) {
                          thisform.closest("div").html("Added")
                        }
                      });
                    });
                  });
                $(function () {
                  $('.class_new_delete').submit('click', function (event) {
                    let thisform = this;
                    event.preventDefault();
                      $.ajax({
                        type: 'POST',
                        url: 'ajax/mylist.php',
                        data: $(this).serialize(),
                        success: function (data) {
                          thisform.closest("div").html("Removed");
                        }
                      });
                    });
                  });
            </script>
    </div>
  • 1
    IDs must be unique. Use classes, not IDs, for repeated elements. – Barmar May 24 '23 at 15:48
  • *How can I assign a unique Id to resolve this?* - don't. Don't use auto-generated IDs, they're more hassle than they're worth. Instead, use DOM navigation. Eg in your form submit event, `let thisform = this;` then in the ajax callback: `thisform.closest("div").html("removed")` – freedomn-m May 24 '23 at 15:50
  • Then see [here](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) for how to reference `this` in the `success:` callback so you reference the current element. – Barmar May 24 '23 at 15:50
  • I agree with the above and there definitely more elegant ways to do this, but why don't you add an id you your query and use that for an element Id? – Ted May 24 '23 at 15:52
  • Also, your if else statement repeats a lot of the same stuff, why not write it once and just swap the values that change depending on the condition? – Ted May 24 '23 at 15:53
  • Changes added to my original post. No dice getting the success to work yet... – colemaniac May 24 '23 at 18:39

1 Answers1

0

It looks like your event itself isn't correct. You have submit('click' and it should be something like .on("submit").

Also, using "context" in the ajax call I'm able to pass $(this) so it allows me to access that inside of the success.

$(function() {
  $('.class_new_add').on('submit', function(event) {
    event.preventDefault();
    $.ajax({
      type: 'POST',
      url: 'https://httpbin.org/post',
      context:$(this),
      data: {"key": "value"},
      success: function(data) {
        $(this).closest("div").html("Added")
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div_new_add" style="display: inline-block;">
  <form id="form-new" style="display: inline-block;" class="class_new_add">
    <input style="display: none" type="text" name="title_home" value="<?php echo $title_full; ?>" />
    <input style="display: none" name="favorite_home" value="favorite_home" />
    <input type="submit" name="btn_password" value="Add" class="class_fav_hover_off">
  </form>
</div>
imvain2
  • 15,480
  • 1
  • 16
  • 21