Sending data to a MySQL database with AJAX / XmlHtttpRequest
Posted: Fri Jun 19, 2009 8:51 am
I've looked through a few tutorials and don't completely understand this, if anyone could look at my code and tell me what exactly I need to change, I'd be grateful.
Edit: I suppose it'd be helpful if you knew what I was trying to do.
Basically, I have a form in the index file, and a sql database that simply consists of an auto_increment id field, and a value field. I want the data from the input form to be put into the value field in the database as a new entry, without refreshing the page, when the button is clicked.
index file:
send.php
Edit: I suppose it'd be helpful if you knew what I was trying to do.
Basically, I have a form in the index file, and a sql database that simply consists of an auto_increment id field, and a value field. I want the data from the input form to be put into the value field in the database as a new entry, without refreshing the page, when the button is clicked.
index file:
Code: Select all
<script language="javascript">
function getXhrObject() {
var xhrObject = false;
// Most browsers (including IE7) use the 3 lines below
if (window.XMLHttpRequest) {
xhrObject = new XMLHttpRequest();
}
// Internet Explorer 5/6 will use one of the following
else if (window.ActiveXObject) {
try {
xhrObject = new ActiveXObject("Msxml2.XMLHTTP");
} catch(err) {
try {
xhrObject = new ActiveXObject("Microsoft.XMLHTTP");
} catch(err) {
xhrObject = false;
}
}
}
return xhrObject;
}
var ajaxCapable = getXhrObject();
if (ajaxCapable) {
// perform some Ajax functionality here
function sendCatch(data) {
//actually send the data to the php script
//loading message
document.write('Sending...');
//send
ajaxCapable.onreadystatechange = checkServerResponse;
ajaxCapable.open("POST", "send.php", true);
ajaxCapable.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxCapable.send("data="+data.value);
}
function displayMessage(el) {
//display success or fail message
if(el == 'SUCCESS') {
document.write('Data sent successfully');
} else {
document.write('There was an error sending the data');
}
}
function doUpdate(data) {
if (sendCatch(data)) {
displayMessage('SUCCESS');
} else {
displayMessage('FAIL');
}
}
}
</script>
<input id="data" type="text" name="data" />
<br />
<script language="JavaScript">
var thedata = document.getElementById('data').value;
</script>
<input type="button" onclick="doUpdate(thedata);" value="Send Data" />
Code: Select all
<?php
function doConnect() {
//connects to the database
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Database Connection Error: ' . mysql_error());
}
mysql_select_db("ajax", $con);
}
doConnect();
$data = $_POST['data'];
$data = mysql_real_escape_string($data);
$query = "INSERT INTO ajax VALUES(NULL, '" . $data . "')";
mysql_query($query) or die(mysql_error());
?>