devirkahan
devirkahan

Reputation: 460

How to have a PHP conditional continue to check after a page has loaded

I have a search box that, after a user has hit the submit button while the results page is loading, I want to show some sort of progress indicator. This simplest I could find is this:

while ( $something == true ) {
  // Echo an extra dot, and flush the buffers
  // to ensure it gets displayed.
  echo ' .';
  flush();

  // Now sleep for 1 second and check again:
  sleep(1);
}

What I would imagine $something should be is simply whether or not the user has submitted the search form yet. The problem with that is that the above PHP code will not know that because the page has already finished loading.

How can I have that PHP execute only after the user has submitted the search form?

Upvotes: 1

Views: 522

Answers (3)

user2158494
user2158494

Reputation: 11

Using jQuery:

$('#submit').click(function(e)){
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "path/to/php/action",
        dataType: "json"
    }).done(function(data){
         while(data.action == 'waiting'){
             $('.somePageClass').html('<p>...</p>');
         }else{
             $('.somePageClass').html('your results');
         }
    });
});

something like that using ajax to call a php function, your php function will have to check whether your waiting or done and return data.action.

this may not be fully correct, but it's an attempt (at least in the right direction).

Upvotes: 0

Pevara
Pevara

Reputation: 14310

PHP is a server side language, so it can not see what is going on in the browser. I will only respond to a request made by the browser. There are 2 ways to achieve what I think you are after.

The ajax way:
To have some sort of live feedback you will need a client side language, wich would be Javascript. I suggest you have a look at jQuery, a javascript library, that is fairly easy to understand. More specificly you will be needing the $.ajax method and the .submit event probabaly

the PHP way:
You could also have your form submit to the same php page the search form is on, and then detect wether the form has been submitted by checking if the form variables exist. Something like this:

if (array_key_exists('search', $_REQUEST) {
 // the form has been submitted
}
else  {
 // the form is not yet submitted
}

That is supposing the search box in your form has the name 'search'

Upvotes: 1

Mchl
Mchl

Reputation: 62395

You can't. You'd need to use JavaScript for that (possibly also AJAX to interact with server side code)

Upvotes: 3

Related Questions