Ajax Requests in a Loop
-
hi,
I’m trying to implement a loop that every time makes a new ajax request; to get an idea this is the javascript code:function showData(data){ console.log(data); } function getData( page_num ){ jQuery(document).ready( function($) { $.ajax( { method: 'POST', dataType : 'json', url : passed_data.ajaxurl, data : { page : page_num, _wpnonce : passed_data.nonce, action : 'get_data' }, success : function(data){ showData(data); } } ) } ); } const pages = document.querySelectorAll('.pages'); for (i = 0; i < pages.length; i++) { getData( pages[i] ); }
and this is the php code:
add_action( 'wp_ajax_get_data', 'get_data' ); function get_data(){ if ( wp_verify_nonce( $_POST['_wpnonce'], 'wp_rest' ) ){ $data = get_page( $_POST['page'] ); echo json_encode( array( 'data' => $data ) ); die(); } else { die(); } }
Ajax work just fine, the problem is that I get “i” times the same set of data (from the last request).
I believe that it’s a problem of timing, that the ajax request fires after the for loop is complete; so at the end it only sees the last value “i” times;
Does anyone have any idea on how to solve this problem?
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
- The topic ‘Ajax Requests in a Loop’ is closed to new replies.