How to use jQuery AJAX.done variables in the following query

I would like to know how to return the var page from the processed method, so next time I click on ".morePlease", it sends the new page value (incremented using my backend php returned and returned).

(function($) {
    var page ='';

$(document).on( 'click', '.morePlease', function( event ) {
    event.preventDefault();
    getMorePosts(page);
})

function getMorePosts(page) { 
    $.ajax({
    url: '<?=$ajaxUrl?>',
    type: 'post',
    data: {
    action: 'ajax_pagination',
    query_vars:'<?=$query?>',
    page: page
    }
    }).done(function(response) {
        var obj=$.parseJSON(response);
        page = obj.page;
    }).fail(function() {
       alert( 'no result ' ); 
    });
}
})(jQuery);
+4
source share
2 answers

You can save it outside to make it global and accessible in all your functions.

  page = 1;
 // now this page will be initialized once on page reload and its value 
 // will exists and changing on entire page
 (function($) {
      $(document).on( 'click', '.morePlease', function( event ) {
         event.preventDefault();
         getMorePosts(page);
      })

     function getMorePosts(page) { 
         $.ajax({
             url: '<?=$ajaxUrl?>',
             type: 'post',
             data: {
                 action: 'ajax_pagination',
                 query_vars:'<?=$query?>',
                 page: page
             }
         }).done(function(response) {
             var obj=$.parseJSON(response);
             page = obj.page;
         }).fail(function() {
             alert( 'no result ' ); 
         });
   }
})(jQuery);
+2
source

Thank you that Meenesh Jain for pointing me in the right direction did not work for me, although I found the global setting with the window. way did.

(function($) {
    window.page = '';

    $(document).on( 'click', '.morePlease', function( event ) {
        event.preventDefault();
        getMorePosts(page);
    })

    function getMorePosts(page) { 
        $.ajax({
            url: '<?=$ajaxUrl?>',
            type: 'post',
            data: {
                action: 'ajax_pagination',
                query_vars:'<?=$query?>',
                page: page
            }
        }).done(function(response) {
            var obj=$.parseJSON(response);
            window.page = obj.page;
        }).fail(function() {
            alert( 'no result ' ); 
        });
    }
})(jQuery);
0
source

All Articles