1. The only thing you need to have and I'm not explaining is a function to get the AJAX xml.
If you don't have it heres the one I use:
Code: Select all
function getXhttp ( )
{
var ajax_request;
if ( window.ActiveXObject ) {
var mSoftVersions = [
'MSXML2.****.5.0',
'MSXML2.****.4.0',
'MSXML2.****.3.0',
'MSXML2.****.2.0',
'MSXML2.****',
'Microsoft.XmlDom',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP'
];
for ( i=0; i<mSoftVersions.length; i++ ) {
try {
ajax_request = new ActiveXObject ( mSoftVersions[i] );
} catch ( e ) { }
}
} else if ( !ajax_request && typeof XMLHttpRequest != 'undefined' ) {
try {
ajax_request = new XMLHttpRequest;
} catch ( e ) { }
} else if ( !ajax_request && window.createRequest ) {
try {
ajax_request = window.createRequest;
} catch ( e ) { }
} else {
ajax_request = false;
}
return ajax_request;
}
2. Okay, now that, that's out of the way, sending a request with AJAX using POST is a lot easier than it seems.
First you declare a function like.. add news or something:
Code: Select all
function add_news ( )
{
//...
}
3. You set up your AJAX Request var and test to see if its available.
Code: Select all
function add_news ( )
{
var xml = getXhttp( );
if ( !xml )
return false; //Usually you alert something but I don't :d
//.. other stuff
}
4. So what we've done so far is set the variable xml to the function.
Then tested the variable wheter its false, if it is, it will return false and end the add_news(); function.
The next part is to change the content-type of the page to submit the form.
Code: Select all
function add_news ( )
{
var xml = getXhttp( );
if ( !xml )
return false; //Usually you alert something but I don't :d
xml.open('POST', 'post_news.php');
xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
5. The only thing left to do is send the form data, so what you want to do is put your fields in variables and send them.
Code: Select all
function add_news ( )
{
var xml = getXhttp( );
if ( !xml )
return false; //Usually you alert something but I don't :d
xml.open('POST', 'post_news.php');
xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var title = ****.getElementById('news_title').value;
var content = ****.getElementById('news_content').value;
//CHECKS DONE HERE.
xml.send('news_title=' + title + '&news_content=' + content);
//ANYTHING EXTRA IS ADDED HERE.
}
6. Now in post_news.php you need to:
* Connect to database
* Insert news
so post_news.php:
Code: Select all
<?php
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$news_title = $_POST['news_title'];
$news_content = $_POST['news_content'];
$news_content = nl2br($news_content);
$query = mysql_query("insert into `newstable` ( `title`, `content` ) values (
'{$news_title}',
'{$news_content}'
);");
mysql_close();
?>