In jQuery you can easily just use their Ajax library. The problem is that I only need it ONE time in my code, so it would not be nessesary to call the whole JavaScript library.
I have this code I have been working on, but I can't seem to get it working. I am trying to start a PHP script by the click of a button. How do I do that?
Here is how far I am right now:
<div onClick="count();">Click!</div>
<script>
function count() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
xhr.open('GET', 'count.php', false);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
while (results.hasChildNodes()) {
results.removeChild(results.lastChild);
}
results.appendChild(document.createTextNode(xhr.responseText));
}
}
xhr.send();
}, false);
}
</script>
And here is the code inside the PHP file:
<?php
mysql_connect("myhost", "username", "password") or die(mysql_error());
mysql_select_db("mydatabase") or die(mysql_error());
mysql_query("INSERT INTO `table` (`field`) VALUES(\'+1\'); ")
or die(mysql_error());
?>
<script>
function count() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
xhr.open('GET', 'count.php', false);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
while (results.hasChildNodes()) {
results.removeChild(results.lastChild);
}
results.appendChild(document.createTextNode(xhr.responseText));
}
}
xhr.send();
}, false); // This Line looks extra. Remove this and try
}
</script>
Very short method.
HTML:
<input type="button" onclick="count()" value="count">
JS:
function count() {
url="yourphp.php";
objX=new XMLHttpRequest();
objX.open("GET",url,false);
objX.send(null);
}