php到javascript并返回

I have a php file that generates some html and do some database queries. And there is some switch case statement. In one particular case I need to send to the user some dialog. If the user press OK I need to to some db queries and if the user press cancel I do not. So I decided to echo out a JavaScript code snippet which contains a confirm statement. So how can I send from the JavaScript the result of the confirm message back to php, and decide make a db query or not.

<?php 
// some code
switch $_REQUEST['action']
case 'save':
echo '<script type="text/javascript">',
     'if (!confirm("text + variables") ) { ajax=new XMLHttpRequest();
                                           ajax.open("POST",filename.php,true);
                                           ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                                           ajax.send("userChoice=false");
                                         }',
     '</script>';
if (!empty($_POST['userChoice'])) {
    echo 'got the variable from javascript!'
    // do some code
}

But unfortunately $_POST['userChoice'] is always empty. Does anybody know why?

You put in the filename without quotes.

Javascript then doesn't know it is a string containing the filename, it thinks it's an object instance called filename with a property php.

ajax.open("POST", "filename.php" ,true);

Don't mix PHP and JS this way,... they are totally different languages, serverside, clientside,.

Build your Javascript a way so it works without PHP.

Let then PHP inject some configuration using:

<script>
var config = <?php json_encode($phpToJs); ?>;
</script>

Try to pass the parameter within the url when calling ajax.open();

Example: filename.php?userChoice=false

You're missing break; and default in switch statment