4

In JavaScript, we have Alert() and Prompt() which open up a popup box for the user.

Is there an equivalent for PHP? $Get_['asdf'] is one way to get user input... any others?

Also, one more question. Is it a requirement that PHP always be executed all at once? Or can it be like JavaScript, where it waits for the user input (e.g. popup box), then executes the rest of the code after that.

Manuel Allenspach
  • 12,467
  • 14
  • 54
  • 76
user4757174
  • 416
  • 2
  • 4
  • 14
  • Take a look at here: http://programmers.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming – Cristik May 22 '15 at 05:32

4 Answers4

9

PHP is a server side language, it can't do alert messages on the client side. But you can use javascript within the php to do the alert.

<script type="text/javascript">
window.alert("Hi There, I am the Alert Box!")
</script>

For Prompt you can do something like this -

<?php

    //prompt function
    function prompt($prompt_msg){
        echo("<script type='text/javascript'> var answer = prompt('".$prompt_msg."'); </script>");

        $answer = "<script type='text/javascript'> document.write(answer); </script>";
        return($answer);
    }

    //program
    $prompt_msg = "Please type your name.";
    $name = prompt($prompt_msg);

    $output_msg = "Hello there ".$name."!";
    echo($output_msg);

?>
SantanuMajumdar
  • 886
  • 1
  • 5
  • 20
  • I tried using the alert for php which you gave, inside a .php page called using AJAX. For some reason, it wouldn't work, even though I put it inside an `echo " ";`. – aravk33 Sep 29 '17 at 11:56
  • if you echo it in the `.php` that is being called via `ajax` it'll come back as the `response`. It won't just echo it, or throw an alert. You then would have to do the alert in the `ajax` caller. – jpgerb Oct 28 '22 at 19:56
2

Nope, there is no equivalent. All php is executed on the server-side only. Unless you're using it at the command-line, which I doubt.

It also cannot wait for user input like javascript, like you wanted. Sorry. You'll have to use ajax for that.

Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
2

That's it:

$shouldProceed = readline('Do you wanna proceed?(y/n): ');
if (strtolower(trim($shouldProceed)) == 'n') exit;
proceed();
  • In JS Window.prompt() displays a dialog with an optional message prompting the user to input some text, as well readline() in PHP. Just one main difference: JS interpretates in your browser so dialog displays in browser, PHP interpretates in "PHP interpretator" (do not know how it names) so a dialog will be displayed in your command line if you proceed your code in it. – Evanh Shumakov Aug 08 '19 at 14:36
1

PHP can run anywhere there is a php interpreter available, that is, on a web server, or as a command line shell script. In the latter case , you could use ...

readline ( "Press Enter to continue, or Ctrl+C to cancel." );
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103