-1

I try to do validation that confirms if the user accepts the request or not.

There is two state of the request, success or failure. But they always return True in the confirm statement.

Why is that and how should I fix it?

An example of code that acts like i said:

<script>
if (confirm('Some Question')) {
    <?php
        if (mssql_query ("some query...")) {
            mssql_query ("some query 2...")
            ?> alert('Succes!'); <?php
        }
        else { ?> alert('Query Fail'); <?php }
    ?>
}
else {
    alert('Fail');
}

Almog
  • 220
  • 1
  • 10
  • 1
    ...because, you're using a lethal injection of both JS/PHP. Why not just use Ajax and JS with PHP on the side, along with the regular "run of the mill" conditional statements? Mixing both always causes headaches, not to mention a potential hangover. – Funk Forty Niner Feb 16 '14 at 21:07
  • Yeah, you need to read up on client side vs server side. If you want javascript to trigger a php script you need to use AJAX, iframes, or page loads. – Ben D Feb 16 '14 at 21:10
  • you should know that PHP executes before Javascript, so mixing your languages like that is a bad idea because your PHP will have already run first. You should send an AJAX request a PHP script that handles all the querying logic and just returns accordingly. – thescientist Feb 16 '14 at 21:10
  • possible duplicate of [Reference: Why does the PHP (or other server side) code in my Javascript not work?](http://stackoverflow.com/questions/13840429/reference-why-does-the-php-or-other-server-side-code-in-my-javascript-not-wor) – deceze Feb 16 '14 at 21:34

1 Answers1

1

I may be jumping to conclusions, but I don't think you understand the difference between the PHP code being executed on the server, and the javascript being executed on the client. The javascript and PHP in your code you have written is not going to execute in the order you might expect it to.

When you first load your .php file, this PHP is going to be executed FIRST by the server:

if (mssql_query ("some query...")) {
        mssql_query ("some query 2...")
        ?> alert('Succes!'); <?php
    }
    else { ?> alert('Query Fail'); <?php }

Notice that the mssql_query() function is being run regardless of the action of the user on the frontend.

Once your PHP has finished executing and if the if statement above is true, the following javascript code will be served to the browser

if (confirm('Some Question')) {
    alert(''Success!);
}
else {
    alert('Fail');
}

Notice that your page has loaded in the browser, none of your PHP is able to be run.

You have to restructure your logic in order to achieve what you want. A quick solution for your case would be to have just 2 files. 1 file with the javascript asking the confirmation of the user, and if confirm() then use either AJAX or a straight redirect of the user to yourscript.php which contains the code for executing the mssql query.

Happy coding!

Cameron
  • 597
  • 1
  • 4
  • 14