« Previous entry | Next entry » Browse > Snippets
Skip to comments (14)
Javascript: AJAX
Posted by JDBurnZ on Apr 30 2008 @ 07:30 :: 1378 unique visits
In my endeavors to strive for that web 2.0 standard, I did a bit of research after after looking at a few example, began piecing together my own AJAX request functions.The script I originally modeled my script after is available at: http://www.captain.at/howto-ajax-form-post-get.php
The version displayed below is a much more powerful and useful version which is fully supported in both Firefox and Internet Explorer, and supports both POST and GET methods!
In the example below, there are two functions you will be calling: ajaxGet, and ajaxPost. As yopu'd assume, ajaxGet is used when passing a url, or a url followed by a string of variables. AjaxPost is used when there is a form on your page, and you would like to submit it without having to refresh the entire page.
CODE: JAVASCRIPT
var http_request = false;
var thisTargetObject = false;
var evalReturn = false;
function displayError(errorMessage) {
window.alert(errorMessage);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
result = http_request.responseText;
if (evalReturn == true) {
start = (result.indexOf("<script>") + 31);
end = (result.lastIndexOf("</script>",start) - 8);
evalString = result.slice(start,end);
if (start && end && start != end) {
eval(evalString);
}
}
document.getElementById(thisTargetObject).innerHTML = result;
} else {
displayError("There was a problem with the request.");
}
}
}
function ajaxPostExecute(targetObject, url, parameters) {
http_request = false;
thisTargetObject = targetObject;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
displayError('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function ajaxPost(fromForm, targetObject, targetPage) {
var getstr = "";
obj = document.getElementById(fromForm).getElementsByTagName('input');
for (i = 0; i < obj.length; i++) {
if (obj[i].type == "text") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "password") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "hidden") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "button") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "file") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "image") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "reset") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "submit") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "checkbox") {
if (obj[i].checked) {
getstr += obj[i].name + "=" + obj[i].value + "&";
} else {
getstr += obj[i].name + "=&";
}
}
if (obj[i].type == "radio") {
if (obj[i].checked) {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
}
}
getstr += "ajax=1&";
obj = document.getElementById(fromForm).getElementsByTagName('textarea');
for (i = 0; i < obj.length; i++) {
getstr += obj[i].name + "=" + encodeURI(obj[i].value) + "&";
}
obj = document.getElementById(fromForm).getElementsByTagName('select');
for (i = 0; i < obj.length; i++) {
getstr += obj[i].name + "=" + obj[i].options[obj[i].selectedIndex].value + "&";
}
ajaxPostExecute(targetObject, targetPage, getstr);
}
function ajaxGet(targetObject, targetPage, eval) {
thisTargetObject = targetObject;
evalReturn = eval;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
displayeError('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open("GET", targetPage, true);
http_request.send(null);
}
var thisTargetObject = false;
var evalReturn = false;
function displayError(errorMessage) {
window.alert(errorMessage);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
result = http_request.responseText;
if (evalReturn == true) {
start = (result.indexOf("<script>") + 31);
end = (result.lastIndexOf("</script>",start) - 8);
evalString = result.slice(start,end);
if (start && end && start != end) {
eval(evalString);
}
}
document.getElementById(thisTargetObject).innerHTML = result;
} else {
displayError("There was a problem with the request.");
}
}
}
function ajaxPostExecute(targetObject, url, parameters) {
http_request = false;
thisTargetObject = targetObject;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
displayError('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function ajaxPost(fromForm, targetObject, targetPage) {
var getstr = "";
obj = document.getElementById(fromForm).getElementsByTagName('input');
for (i = 0; i < obj.length; i++) {
if (obj[i].type == "text") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "password") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "hidden") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "button") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "file") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "image") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "reset") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "submit") {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
if (obj[i].type == "checkbox") {
if (obj[i].checked) {
getstr += obj[i].name + "=" + obj[i].value + "&";
} else {
getstr += obj[i].name + "=&";
}
}
if (obj[i].type == "radio") {
if (obj[i].checked) {
getstr += obj[i].name + "=" + obj[i].value + "&";
}
}
}
getstr += "ajax=1&";
obj = document.getElementById(fromForm).getElementsByTagName('textarea');
for (i = 0; i < obj.length; i++) {
getstr += obj[i].name + "=" + encodeURI(obj[i].value) + "&";
}
obj = document.getElementById(fromForm).getElementsByTagName('select');
for (i = 0; i < obj.length; i++) {
getstr += obj[i].name + "=" + obj[i].options[obj[i].selectedIndex].value + "&";
}
ajaxPostExecute(targetObject, targetPage, getstr);
}
function ajaxGet(targetObject, targetPage, eval) {
thisTargetObject = targetObject;
evalReturn = eval;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
displayeError('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open("GET", targetPage, true);
http_request.send(null);
}
An example using the GET method:
CODE: HTML
<a href="#" onclick="ajaxGet('mainBody', 'manage.companies.php', true);">Manage</a>
An example using the POST method:
CODE: HTML
<form method="get" action="#" id="loginForm">
Login Name: <input type="text" name="loginName" /><br />
Password: <input type="password" name="password" /><br />
<br />
<button onclick="ajaxPost('loginForm', 'mainBody', 'login.php');">Log Me In!</button>
</form>
<div id="mainBody">My text will be replaced with the result from login.php!</div>
Login Name: <input type="text" name="loginName" /><br />
Password: <input type="password" name="password" /><br />
<br />
<button onclick="ajaxPost('loginForm', 'mainBody', 'login.php');">Log Me In!</button>
</form>
<div id="mainBody">My text will be replaced with the result from login.php!</div>
Additional Notes:
- When using the ajaxPost function, set the form element's method to get NOT post. The reason for this is we want javasscript to submit the post, not the element. In Internet Explorer, this causes some issues and things won't work you way they should if you use method="post".[/item]
- In PHP, if you encounter a PHP syntax error in the ajax requested file, it may not display any page or information at all, not even the PHP errors.[/item]
- If the page you are loading dynamically contains javascript, you will want to set the third optional value to true. This will pass all your scripts through the eval() function which is required if you want the scripts to work correctly.[/item]
14 comments posted so far
Add your own »
2. On Mar 06 2009 @ 16:52 guest wrote:
dofuslove is a barbaric fantasy-themed MMORPG developed by Funcom. WE have sell the first game dofus kamas.The game brings players to experience live violent from the Hyborian Age, a fantasy setting created by Robert E. Howard. Amidst the chaotic blood-bath surroundings, there is a civilized system of commerce and currency. Players in Age of Conan: Hyborian Adventures bargain for goods and services using pieces of gold, silver, copper and tin as their median of trade. And we sell an other game coin cabal alz.and the others game,like Ms gold,eve isk.and As players struggle to become the legend of the Hyborian Age, the ealth in gold is not a factor to be neglected.dofus kamas
aoc gold
cabal alz
ms gold
eve isk
jjsgame
dofus kamas
buy dofus kamas
aoc gold
cabal alz
ms meso
eve isk
maplestory meso
perfectworld gold
wow gold
war-europe gold
2moons gold
lineage2 adena
lotro gold
secondlife gold
gaiaonline gold
rf dalant
bocgold
3. On Mar 09 2009 @ 09:58 guest wrote:
Weaknesses of world of warcraft gold the client-server model used by World of Warcraft have been wow power levelingexploited in order to crash the cluster of servers that make up a realm. Exploits also include characters being able to instantly change location or teleport. The situation Cheap Wow Goldbecame worse when trying to coordinate activities across a number of players cheapest wow goldor guilds on the same realm.World of Warcraft Lead Producer, stated that new realms would be introduced to relieve the burden on existing ones. Existing realms would be upgraded.Although the game wow gold follows a similar model to others in the genreand was noted for having buy cheap wow gold many familiar concepts from roleplaying games, the new approaches wow gold cheapto reduce pauses between game encounters was well liked. At various times, World of Warcraft players have experienced problems with connecting to and logging in to wow gold for salethe game. Sudden server crashes that would force realms offline also occurred.
4. On May 20 2009 @ 06:48 guest wrote:
(CNN) All apologies,<a href="http://www.wowgoldbag.fr" title="wow gold">wow gold</a> but here we are now, 17 years after<a href="http://www.tbcgold.fr" title="wow gold">wow gold</a> Nirvana's breakthrough<a href="http://www.srogold.fr" title="wow gold">wow gold</a> album irreversibly changed music, and the naked baby pictured<a href="http://www.wowmine.fr" title="wow gold">wow gold</a> on its cover is still <a href="http://www.mmotao.fr" title="wow gold">wow gold</a>chasing dollars.<a href="http://www.world-of-warcraft-gold.net" title="wow gold">wow gold</a>Spencer Elden, 17,<a href="http://www.wow-gold-kaufen.com" title="wow gold">wow gold</a> recreates his pose from 1991's<a href="http://www.wowgold.ws" title="wow gold">wow gold</a> Nirvana "Nevermind" album.Spencer Elden,<a href="http://www.wowtao.fr" title="wow gold">wow gold</a> 17, recreates his pose from 1991's Nirvana "Nevermind" album.Click to view previous image<a href="http://www.wowgoldlive.de" title="wow gold">wow gold</a>1 of 4Click to view next imageSpencer Elden, <a href="http://www.wowgoldlive.fr" title="" title="wow gold">wow gold</a>the underwater infant pursuing a dollar bill on the cover of 1991's "Nevermind."
5. On May 20 2009 @ 06:48 guest wrote:
(CNN)wow gold All apologies, wow goldbut here we are now, wow gold17 years after Nirvana's breakthrough album wow goldirreversibly changed music,wow gold and the naked baby pictured wow goldon its cover is still chasing wow golddollars.Spencer Elden,wow gold 17, recreates his pose from 1991'swow gold Nirvana "Nevermind" album.wow goldSpencer Elden, 17, recreates hwow goldis pose from 1991's Nirvana "Nevermind" album.6. On May 20 2009 @ 06:49 zengxu wrote:
(CNN)wow gold All apologies, wow goldbut here we are now, wow gold17 years after Nirvana's breakthrough album wow goldirreversibly changed music,wow gold and the naked baby pictured wow goldon its cover is still chasing wow golddollars.Spencer Elden,wow gold 17, recreates his pose from 1991'swow gold Nirvana "Nevermind" album.wow goldSpencer Elden, 17, recreates hwow goldis pose from 1991's Nirvana "Nevermind" album.7. On May 20 2009 @ 06:49 zengxu wrote:
(CNN)wow gold All apologies, wow goldbut here we are now, wow gold17 years after Nirvana's breakthrough album wow goldirreversibly changed music,wow gold and the naked baby pictured wow goldon its cover is still chasing wow golddollars.Spencer Elden,wow gold 17, recreates his pose from 1991'swow gold Nirvana "Nevermind" album.wow goldSpencer Elden, 17, recreates hwow goldis pose from 1991's Nirvana "Nevermind" album.8. On May 27 2009 @ 06:17 xiang wrote:
In the Rainywow gold Season of SpringItwow power leveling drizeles endlessly world of warcraft goldduring the rainy wow goldseason in spring,wow power levelingTravellers along wow goldthe road look wow goldgloomy and miserable.9. On May 27 2009 @ 06:17 cqx wrote:
here once wasreplica handbags a king whoreplica watches offered a prizeDesigner clothing to the artistDesigner replica handbags who would paint Wholesale jewelrythe best picture Replica rolex watchesof peace.replica handbag Many artists tried. hair straightenersThe king looked GHDat all the chi hair straightenerspictures. Butreplica handbags there were wholesale handbagsonly two he replica designer handbagsreally liked, replica watchand he had swiss replica watchesto choosereplica rolex watches between them. puma shoesOne picture was nike shoesof calm lake.womens clothes The lake was ed hardy clothinga perfect mirror Replica Handbagsfor peaceful Replica Watchestowering mountainsreplica designer handbags all around it.Coach Handbags Overhead was a Gucci Handbagsblue sky with Rolex Watchesfluffy white clouds.Ladies Shop If this wereGucci Handbags not bad enough,replica prada handbags the neurosurgeonwholesale omega watches further shockedAdidas Shoes my family by lacoste Clothes what life woulded hardy caps be like In ed hardy discounts the Rainy Season ed hardy onlineof SpringIt ed hardy shirtsdrizeles endlessly ed hardy womenduring the rainyTiffany Bracelet season in spring,Tiffany EarringsTravellers along Tiffany jewellersthe road look Tiffany jewelrygloomy and miserable.Tiffany ringsWhen I ask a tiffany silvershepherd boy where tiffany silverI can find Tiffany jewellersa tavern TravellersTiffany jewelry along the Tiffany Braceletroad look gloomy Tiffany Earringsand miserable.Tiffany ringsWhen I ask a shepherd boy10. On May 27 2009 @ 06:17 cuicui wrote:
I remember quiteghd hair straighteners clearly now whenchi hair straighteners the story happened.cheapest ghd hair straighteners The autumn chi turbo hair straightenerleaves werereplica juicy couture handbags floating in 1 cheap LV replica handbagsmeasure down toreplica fendi handbags the ground,wholesale designer handbags recovering the lake,wholesale watches where we used replica rolex watchesto swim likecheap replica breitling watches children, under the cheapest chanel watchessun was therecheap nike shoes to shine. replica fashion shoesThat time wereplica cheap clothes used to be replica abercrombie fitch clothinghappy. Well Ireplica cheap handbags wholesale thought we were.replica chanel handbags But the truthgucci Designer handbags replica was that you replica fashion watches wholesalehad been 2)replica wholesale handbags cheaplonging to leaveReplica best cheap Handbags me, not daring Replica Louis Vuitton bagto tell me. replica Prada handbags wholesaleOn that precious cheap hermes handbag replicanight, watching the lake,vaguely 3conscious11. On Jul 09 2009 @ 12:08 guest wrote:
HD DVD Burning,How Do I Burn Videos to DVD,
DVD Music Burning Software,
DVDClone Software,
CD DVD Burner,
AVI DVD Burner,
MPEG to DVD Burner,
MOV to DVD Burner,
Burn Mp4 to DVD,
Burn WMV to DVD,
DVD Burner for Mac
12. On Jul 14 2009 @ 04:26 guest wrote:
buy wow goldmy wow power leveling
buy wow gold
good wow power leveling
BUY wow gold
my wow power leveling
CHEAP rs gold
cheap wow power leveling
CHEAPEST lotro gold
MY aion gold
buy wow gold
cheap wow gold
CHEAPEST wow gold
13. On Jul 14 2009 @ 08:52 guest wrote:
AVI to DVD Converter,AVI to DVD Creator,iPhone Ringtone Maker for Mac,AVI Converter OS X,VOB Converter OS X,AVCHD Video Converter,FLV Converter,PowerPoint Converter,AVCHD Converter,Blue-Ray ripper,FLV to MOV Mac,VOB to DVD,HD Video Converter,iPod Playlist Transfer14. On Jan 05 2010 @ 14:56 uggbaileybutton wrote:
bailey button uggs-ugg boots cheap
ugg boots uk
ugg classic
1. On Apr 30 2008 @ 07:31 JDBurnZ wrote:
I've updated my post. Now, you may choose to pass an additional parameter to the ajax functions, allowing you to force javascript to run your newly accessed code through the eval() function.If you have any javascript within <script> tags, you will want to make sure this is set to TRUE. If you do not, your scripts won't work when loaded on the fly!
:)