search

Home  >  Q&A  >  body text

How to get the value printed on the screen while waiting for ajax result?

I am using jQuery ajax to send an ajax request to a php file.

$.ajax({
            url: VIP_AJAX_URL + '/add',
            data: 'slug=' + slug,
            method: 'POST',
            beforeSend: function () {
                Swal.fire({
                    title: '请稍候..',
                    html: '我们正在检查。 <br/>这个过程可能需要一些时间。',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading()
                    }
                })
            },
            success: function (res) {
                if (res !== 'success') {
                    Swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        html: res,
                    })
                    return;
                }

                console.log(res);
            }
        })

While this request is going on, I am printing to the screen at intervals in a php file.

echo 'abc';
sleep(5);
echo 'def';
sleep(5);
echo 'ghi';

But after all processes are completed, the ajax process is terminated. I want to get the value printed on the screen while the process is in progress.

For example, I want to get the value of 'abc' when the request is made, 'def' after 5 seconds, and 'ghi' after 10 seconds. How can I do this? I want to achieve this without using sessions, cookies or databases.

P粉252116587P粉252116587488 days ago659

reply all(1)I'll reply

  • P粉638343995

    P粉6383439952023-09-16 21:53:23

    No, you can’t do this

    You can only do this on the front end

    You can get the response periodically and add it to the html view using append() so it keeps growing

    function getLog() {                
    fetch("https://gist.githubusercontent.com/prabansal/115387/raw/0e5911c791c03f2ffb9708d98cac70dd2c1bf0ba/HelloWorld.txt").then(async e=>{
            let t = await e.text()
            document.getElementById("log").innerHTML += t+"<br/>"
        })
    }
    setInterval(getLog, 1000)
    <div id="log"></div>

    I often use this when showing progress in JavaScript, such as during the php artisan migrate process on Laravel

    reply
    0
  • Cancelreply