[javascript] Send data from javascript to a mysql database

I have this little click counter. I would like to include each click in a mysql table. Can anybody help?

var count1 = 0;
function countClicks1() {
count1 = count1 + 1;
document.getElementById("p1").innerHTML = count1;
}


document.write('<p>');
document.write('<a href="javascript:countClicks1();">Count</a>');
document.write('</p>');

document.write('<p id="p1">0</p>');

Just in case anybody wants to see what I did:

var count1 = 0;
function countClicks1() {
count1 = count1 + 1;
document.getElementById("p1").innerHTML = count1;
}
function doAjax()
$.ajax({
   type: "POST",
   url: "phpfile.php",
   data: "name=name&location=location",
    success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });
}

document.write('</p>');
document.write('<a href="javascript:countClicks1(); doAjax();">Count</a>');
document.write('</p>');
document.write('<p id="p1">0</p>');

This is phpfile.php which for testing purposes writes the data to a txt file

<?php
$name = $_POST['name'];
$location = $_POST['location'];
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $name);
fwrite($fh, $location);
fclose($fh);
?>

This question is related to javascript mysql

The answer is


The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

http://api.jquery.com/jQuery.ajax/


You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".