skip to Main Content

I have and array of data by ajax get method. I output this data by its index number as data[0]. for next data I click on a button and need to update the index “here 0” in data to get data[1] and so on. Here is my code, I have tested with defining id after .done but doesn’t work.

     $.ajax({
        url: `/ajaxweblog`,
        id: 0,
      }).done(function (data) {

        $("#rast").on('click', function () {
          this.id += 1;
        });
        $(".title-of").html(data[this.id]['title']);
        $(".subtitle-of").html(data[this.id]['subtitle']);
        $(".thearticel").html(data[this.id]['body']);
        $(".article-img").attr('src', '/images/articles/' + data[this.id]['image']);
      })

2

Answers


  1. Firstly remove click handle code that you inserted inside ‘.done’

    $("#rast").on('click', function () {
    this.id += 1;
    });

    then you have to keep a copy of response object and on click of a button (or change in the id), you have to pass updated JSON data for table to render

    Login or Signup to reply.
  2. let index = 0;
    let data;
    
    function updateDOM() {
      $('.title-of').html(data[index]['title']);
      $('.subtitle-of').html(data[index]['subtitle']);
      $('.thearticel').html(data[index]['body']);
      $('.article-img').attr('src', '/images/articles/' + data[index]['image']);
    }
    
    $("#rast").on('click', function() {
      index += 1;
      // check if the data variable has been assigned a value and if the next index exists
      if (data && data[index]) {
        updateDOM();
      }
    });
    
    // 'id' is not a valid key for the $.ajax settings object
    $.ajax({
      url: '/ajaxweblog'
    }).done(function(res) {
      data = res;
      updateDOM();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search