Reputation: 129
I want to update my database after a condition in javascript. What I do now is something like:
<a href="#" onclick="hello()">Update me</a>
<srcipt>
function hello(smthing)
{
if(smthing == true)
{
<?php //Update database table ?>
}
}
<script>
I have also tried to update my table according an example in w3schools (http://www.w3schools.com/ajax/ajax_example.asp):
<script>
function hello(smthing)
{
if(smthing==true)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","db_update.php",true);
xmlhttp.send();
}
}
</script>
In the first case it updates my table even if the variable smthing = false (but if i enter an alert("hi") inside the if, the alert will be displayed only if 'smthing' is true.
In the second case nothing happens. :/
Any help or guidance pls?
Upvotes: 0
Views: 2046
Reputation: 3845
Javascript is client side scripting language.So it cannot communicate directly with database.
Only Server side scripting language can interact with database through its library functions.
So if you need to update data in database on condition of javascript variable you can accomplish it using ajax technology.
Through AJAX code snippet it can communicate with server in background without reloading the web page using XMLHttpRequest Object.
Please refer the example mentioned in following URL which uses ajax technique for communication with database
http://www.w3schools.com/php/php_ajax_database.asp
Upvotes: 1
Reputation: 7930
You need to study the difference between client-side and server-side code. JavaScript is client-side; executed on the client computer. PHP is server-side; executed on the server computer. The two do not mix the way you are trying to use them.
Whatever PHP code you put into the JavaScript code is executed on the server before the JavaScript is even recognized by the browser as JavaScript code. Whatever logic is happening in JavaScript has no effect on PHP. They should be considered two completely separate - and incompatible - technologies. PHP is only ever used to generate JavaScript code, not to work with it. Only by requesting another PHP page can client-side code execute PHP code.
Your second snippet is using AJAX to try to do just that; to make a completely new request in the background for another PHP script. Based on your comment, I'm guessing you haven't studied AJAX very thoroughly either? It's not at all a difficult thing to figure out, once you get the hang of the whole client-side vs server-side issue.
Upvotes: 4