Execute MySQL only if JS if = true – PHP




I’ve got a mysql query that I’d like to process *only* if a javascript if is true. Is that possible?

Something like this:

<script language="javascript">
if (condition is true) {
$query = "UPDATE table SET example = '3' WHERE id = '1'";
$result = mysql_query($query);

Somehow, as soon as the web is loaded, the query is sent.

Thank you 🙂


What you are trying to do above won’t work because php code is processed on the server-side (before browser gets the page content) and javascript code on client-side (after the php script processed and page downloaded by the browser).

So you have to find a way to check if javascript is enabled within your php script, and here it is Servers side JavaScript detection in PHP4

EDIT: I thought you want to detect javascript at first, but now I see you need something different. Well you can do what you need through an XMLHttpRequest (AJAX). A simple AJAX tutorial can be found at: AJAX Tutorial

And here is more to show why the code above won’t work:

<script language="javascript">
if (0) {
echo $city;

Browser always displays ‘Paris’ because php code is already processed and browser just gets the resulting page.

IMPORTANT NOTE: Using AJAX or any other javascript-based validations/tests does not guarantee that your php script cannot be run without passing the validation/test. You can only secure your test through server-side validations.


Yea, serdar is correct. Doing this the way you are trying is not possible.

The key thing to remember is that PHP is a server-side language, executed by the server to create the content that is to be sent to the client.
Javascript is a client-side language, which is sent as a part of the content that PHP creates and executed by the client’s browser.

Neither of them can directly work with the other simply because they are not being executed by the same computer. When the Javascript is executed, the PHP code has already been executed and closed.

But, like serdar suggested, you can use AJAX to get around this.
An AJAX request is basically just your Javascript requesting another page from the server. If you want the client code to execute a SQL query on the server, you will have to create a PHP page on the server that executes the query, and call that page from you Javascript by using AJAX.


Thank you both, I’ll try it now and let you know how it goes 🙂


Worked just fine, topic solved 🙂

(PS: no edit button?)



Edit button disappears after 5 minutes, I think. What do you want to edit?


Nothing, was trying to avoid double posting I did above 😛