How to execute MySQL Statements within JavaScripts with AJAX

Currently i am developing an administration software for a physiotherapy center. Therefor i simply use PHP and MySQL, so XAMPP was a very comfortable solution. As the complexety of the system grows i had to broaden my horizon and find some tricky solutions to achieve the surreal requirements of my employer. People always want everyhing "flexibel", fast, "automatically",... properties which are very hard to reach within a software. So someday i encountered a very hard problem which took me a long time to solve it (although, afterwards it wasn't so difficult). I had to process some data within my database, which was generated and accessed via JavaScript. If someone has programmed a little bit with PHP before, its not that hard to get content of a PHP-Variable within JavaScript, but its not so easy to process some JavaScript-Variables within an MySQL Statement without reloading the page. So a solution had to be found. After hours of internet surfing and talking to some programmers i found it, my holy grail, AJAX.
1 answer

Howto implement a MySQL execution within JavaScript with Ajax

Step 1: Create the HttpRequest

function createXMLHttpRequest() {

var ua;

if(window.XMLHttpRequest) {
try {
ua = new XMLHttpRequest();
} catch(e) {
ua = false;
}
} else if(window.ActiveXObject) {
try {
ua = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
ua = false;
}
}
return ua;
}

Step 2: Create a function where you call your external MySQL
This function executes the file "abmelden.php" with the parameters "t_id" and "k_id".

function abmelden(teilnehmer, kurs) {
var req1 = createXMLHttpRequest();
req1.open('get', 'abmelden.php?t_id=' + teilnehmer + '&k_id=' + kurs);
req1.send(null);
}

Step 3: Write your MySQL-Script
Now just write down your MySQL-Query in the file "abmelden.php" and that's it.

mysql_query("DELETE FROM rechnung WHERE r_t_id ='".$_GET[t_id]."' and r_k_id ='".$_GET[k_id]."'");

You successfully executed your SQL-Query without reloading the page.
Ajax is really great ;)

Taggings: