• Resolved antonop4u

    (@antonop4u)


    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)
  • Your javascript function getData encloses a function handler for the document.ready event. The page_num that you pass in there is set to the the last one called because each call is replacing the ready handler.

    Thread Starter antonop4u

    (@antonop4u)

    Hi Joy, thank you for your prompt answer, I’d figured it was something like that. Any idea on what shell I do to make it work?

    You would be better off just filling in the page content on the server before the page is sent to the browser.

    But typically, the entire javascript is enclosed in the document.ready handler, not just inside one function.

    Thread Starter antonop4u

    (@antonop4u)

    Joy, Thank you once more for your prompt help, yes that’s what I will do.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Ajax Requests in a Loop’ is closed to new replies.