I’m posting my GET and POST ajax code it will hopefully be useful to some people.
I searched a lot to find some simple code as i didn’t need to validate the forms. So many scripts didn’t work properly or seemed unnecesserily complicated for my requirements.
The code has been adapted from
http://www.w3schools.com/ajax/def
the GET from:
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
Hope you find this helpful!
//Set up the XMLHttpRequest
var http = createRequestObject();
function createRequestObject() {
var objAjax;
var browser = navigator.appName;
if(browser == “Microsoft Internet Explorer”){
objAjax = new ActiveXObject(“Microsoft.XMLHTTP”);
}else{
objAjax = new XMLHttpRequest();
}
return objAjax;
}
//THE GET
function getNewContent(){
http.open(‘get’,'newcontent.php’);
http.onreadystatechange = updateNewContent;
http.send(null);
return false;
}
function updateNewContent(){
if(http.readyState == 4){
document.getElementById(‘Content’).innerHTML = http.responseText;
}
}
//THE POST
function postForm() {
var url = “formentry.php”;
var formtag = document.getElementById(‘fmfield’).value;
var params = “newfield=” + formfield;
http.open(“POST”, url, true);
//Send the proper header information along with the request
http.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
http.setRequestHeader(“Content-length”, params.length);
http.setRequestHeader(“Connection”, “close”);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
document.getElementById(‘fomentered’).innerHTML = http.responseText;
document.getElementById(‘fmfield’).value = “”;
}
}
http.send(params);
}
the functions are called through an onclick event
e.g.
GET <a href=”#” onclick=”getNewContent()”>New Content</a>
POST <a href=”#” onclick=”postForm()”><img src=”Submit.gif”></a>
I couldn’t get it to work properly with a button with type image and i wanted an image so i did it with an <a> tag – i think it works with a normal <input type=”button” onclick=”postForm()”> But it won’t work if you have an <input type=”submit”> button.
I am still trying to figure out how to get it to work when the user presses return or enter – it calls the postForm() but refreshes the page.
If any one can help me on this please comment!!