Skip to content Skip to sidebar Skip to footer

Scroll To Bottom Of Div Using Jquery If Ajax Returns Success

I have this Div which includes the users messages where the newest message is right at the very bottom of the Div and initiates a scroll bar if the messages start to go lower than

Solution 1:

When your script is done, you can use the following script:

$content[0].scrollTop = $content[0].scrollHeight;

Example:

$.ajax({
  url: 'system/reply_system.php',
  type: 'POST',
  dataType: 'json',
  data: $('#reply').serialize(),
  success: function(data) {

    console.log("success");
    var $content = $(".list-group-message");

    $content.text(data); // Here you have to insert the received data.
    $content[0].scrollTop = $content[0].scrollHeight;

    // Second ajax
    $.ajax({
      url: 'system/sars_system.php',
      type: 'POST',
      dataType: 'json',
      data: $('#reply').serialize(),
      success: function(data) {
        $content.text(data); // Here you have to insert the received data.
        $content[0].scrollTop = $content[0].scrollHeight;
      },
      error: function(e) {
         //called when there is an error
         console.log('fail');
      }
    });

  },
  error: function(e) {
    //called when there is an error
    console.log('fail');
  }
});

Hope it helps.


Solution 2:

Try like this:

$.ajax({
    url: 'system/sars_system.php',
    type: 'POST',
    dataType: 'json',
    data: $('#reply').serialize(),
    }),
    success: function(response) {
        console.log(response);
        var $content = $(".list-group-message");
        $content[0].scrollTop = $content[0].scrollHeight;
    },
    error: function(response) {
        console.log(response);
    }
});

Solution 3:

This is the one that how I approached. First access the parent div that you want to load the data. Then scroll down using jquery.

$.ajax({
        type: "GET",
        url: baseURL + "notification/get_load_notif_member_message",
        data: "member_id=" + member_id + "&message_id=" + message_id,
        contentType: 'html',
        success: function (html) {
            $('.msg_history').html(html);
            $("input[name='text']").val('');
            var $content = $(".msg_history");
            $content[0].scrollTop = $content[0].scrollHeight;
        },
        error: function (html) {
            $('.msg_history').html('Something went wrong. Please try again.');
        }
    });

Post a Comment for "Scroll To Bottom Of Div Using Jquery If Ajax Returns Success"