Home > Blockchain >  Execute js code inside a ajax handler function in wordpress
Execute js code inside a ajax handler function in wordpress

Time:10-11

I focused on a wordpress plugin development. In this plugin, I'm trying to design a progress bar that moves according a backend process. After an extensive search, I understood that it is possible by using jquery methods.

From this reference, I wrote following code in plugin's main php file:

<?php
add_action( 'admin_footer', 'my_action_javascript' );

function my_action_javascript() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {

    var element = document.getElementById("myBar"); // It is my bootstrap progress bar
    var width=0; // Initial width (%)
    var add=1; // 1% incrementation variable for progress bar

    var data = {
        'action': 'my_action',
        'whatever': 1234
    };
    
    jQuery.post(ajaxurl, data, function(response) {
        alert('Got this from the server: '   response);
    });
});
</script> <?php
}

add_action( 'wp_ajax_my_action', 'my_action' );

function my_action() {

$whatever = $_POST['whatever'];

echo $whatever;

wp_die();
}

It works fine, the response shows on alert field. However, when I add following js code into that my_action function:

add_action( 'wp_ajax_my_action', 'my_action' );

function my_action() {

$repeater = 0;
$controller = 0;

for ($i=1; $i <= 4000 ; $i  ) { 
    if ($repeater <= 10) {
        $controller  ;
        if ($controller == 40) { ?>
            //code starts here
            <script type="text/javascript">
            element.style.width = width   add   "%"; 
            element.innerHTML = width   add   "%";
            width = width add;  
            </script>
            <?php 
            sleep(1);
            $controller=0;
            $repeater  ;
        }
    } else {
        return;
    }
}

wp_die();
}

It doesn't work. I guess the nature of ajax process in wordpress, the core is waiting for finishes all php codes in function and it doesn't allow run another js code. So, if I miss some point or there is a better way to achieve this; I would be grateful if you help.

CodePudding user response:

I think you need to flush after every <script>

try to add before sleep()

ob_flush();
flush();
sleep(1);

if you don't flush, all the output is sent at the end of the execution or when outptbuffer is full.

That means that now you send all script at once

CodePudding user response:

If i think of one of the many plugins in wordpress that does something similar i always found that they divide the task in very small "chunks". For every chunk they make a new ajax call, get a response, update the progress bar and repeat, until the full task is over.

In your case say that you have 100 products to import you should split them in like 10 request with 10 item each and return the updated % accordingly.

This design is much more easier to implements and it could give better UX to the user

  • Related