eire web design home page contact eire-web design eire web design and development site map
stepping on in business
• Ajax load content from another file using POST or GET

Ajax load content from another file using POST or GET



These is a simple Ajax example that will load content into the page from another file without browser refresh.
05-Oct-2007 – We have updated the javascript to allow the use of forms to be submited using POST.

Click here for Demo » OR DOWNLOAD THE AJAX SAMPLE

How does it work?

First we need to create the javascript file with the following code:

var ewd_domain = 'http://www.eire-webdesign.ie/'; //set domain
var ewd_loading_img = ewd_domain + 'images/loading.gif';//set image path
var ewd_loading_msg = 'Loading Data...';//set loading message
var xmlhttp_obj = false;       

//create the XMLHttpRequest
function ewd_xmlhttp(){
if (window.XMLHttpRequest){ // if Mozilla, Safari etc
xmlhttp_obj = new XMLHttpRequest();
}else if (window.ActiveXObject){ // if IE
try{
xmlhttp_obj = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
try{
xmlhttp_obj = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
}
}    

}else{
xmlhttp_obj = false;
}
return xmlhttp_obj;
}    

//get content via GET
function ewd_getcontent(url, containerid){
var xmlhttp_obj = ewd_xmlhttp();
document.getElementById(containerid).innerHTML = '' + ewd_loading_msg;
xmlhttp_obj.onreadystatechange=function(){
ewd_loadpage(xmlhttp_obj, '', containerid);
}
xmlhttp_obj.open('GET', url, true);
xmlhttp_obj.send(null);
}       

function ewd_loadpage(xmlhttp_obj, content, containerid){
if ( xmlhttp_obj.readyState == 4 && xmlhttp_obj.status == 200 ){
document.getElementById(containerid).innerHTML = xmlhttp_obj.responseText;
}
}       

//functions for posted values from forms vis POST
function ewd_getcontent_post(url, content, containerid){
var xinput = content;
var xmlhttp_obj = ewd_xmlhttp();
document.getElementById(containerid).innerHTML = '' + ewd_loading_msg;
xmlhttp_obj.open('POST', url, true);
xmlhttp_obj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp_obj.onreadystatechange = function() {
ewd_loadpage(xmlhttp_obj, content, containerid);
}
xmlhttp_obj.send(content);
}   

//convert form data sent to POST CONTENT
function ewd_submit_form(page_to,form_name,containerid) {
var content = ewd_convertFormDataToPostContent(form_name);
ewd_getcontent_post(page_to, content, containerid);
}       

function ewd_convertFormDataToPostContent(form_y){
var f=document.getElementById(form_y);
var content_to_submit = '';
var form_element;
var last_element_name = '';
for (i = 0; i < f.elements.length; i++){
form_element = f.elements[i];
switch (form_element.type){
// text fields, hidden form elements
case 'text':
case 'hidden':
case 'password':
case 'textarea':
case 'select-one':
content_to_submit += form_element.name + '=' + escape(form_element.value) + '&';
break;
// radio buttons
case 'radio':
if (form_element.checked){
content_to_submit += form_element.name + '=' + escape(form_element.value) + '&';
}
break;
// checkboxes
case 'checkbox':
if (form_element.checked){
// Continuing multiple, same-name checkboxes
if (form_element.name == last_element_name){
// Strip of end ampersand if there is one
if (content_to_submit.lastIndexOf('&') == content_to_submit.length - 1){
content_to_submit = content_to_submit.substr(0, content_to_submit.length - 1);
}
// Append value as comma-delimited string
content_to_submit += ',' + escape(form_element.value);
}else{
content_to_submit += form_element.name + '=' + escape(form_element.value);
}
content_to_submit += '&';
last_element_name = form_element.name;
}
break;
}//end switch
} //end for
// remove trailing separator
content_to_submit = content_to_submit.substr(0, content_to_submit.length - 1);
return content_to_submit;
}

Now create the page that will hold the content to be displayed (“content_ajax.php”):

	First we create the link that "onclick" will populate the div or span id - "div_populate".
	Make sure you have the javascript source "ajax.js" included into this file.

	• Get Data 1 »
	  
	• Get Data 2 »
or you can use a form to submit data (using "onchange" on the form input or "onclick" on the submit button):
Now and example using a form to post the data Here is the place where the data from the "content_ajax.php" page will be displayed. © Eire-Web Design Ireland

This is the code for the file that will be called:

$datax = $_POST['test'];
$datax1 = $_POST['test1'];
$datax2 = $_POST['test2'];
if($datax != "" || $datax1 != "" ){
echo "data posted: " . ($datax != "" ? "first input = ".$datax : "").
($datax1 != "" ? "second input = ".$datax1 : "").
($datax2 != "" ? "checkbox input = ".$datax2 : "checkbox input = unchecked")."";
exit();
}       

$data = "1";
if(isset($_GET['data']) && $_GET['data'] != ""){
$data = $_GET['data'];
}
if($data =="1"){
?>
 Welcome to Web Design Dublin Ireland - Eire-WebDesign.ie   This is the second link
}elseif($data == "2"){ echo "This is the second data that has been sent using GET."; }elseif($data == "3"){ $datax = htmlspecialchars($_GET['test']); echo "data posted: " . $datax; } ?>

Tags:

This entry was posted on Monday, October 15th, 2007 at 9:00 am and is filed under Ajax. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 4.00 out of 5)
Loading ... Loading ...


  • 17 Responses to “Ajax load content from another file using POST or GET”

aliroman Says:
October 17th, 2007 at 8:18 pm

This is an amazing example, and I am really thankful to Louie who saved me a lot of time, and provided a real quick solution. Thats a great script and I am sure web developers of all level will love it.

thanks..

Louie Says:
October 17th, 2007 at 8:19 pm

No problem. Glad I could help.

I am making small changes to it as I write this and I will upload the new version soon.

Is more compact.

'Select Box' Selection Function - Irish SEO, Marketing & Webmaster Discussion Says:
November 12th, 2007 at 10:35 pm

[...] is an example for you. Give it a shot and you’ll get the hang of it quickly: Ajax load content from another file using POST or GET | Eire Web Design __________________ :. Used Car Sales :. Car Parts & Accessories :. Car Styling :. Auto [...]

Mike Says:
September 23rd, 2008 at 12:51 am

How do you change a form field so that it can uploading image file?

case ‘text’:
case ‘hidden’:
case ‘password’:
case ‘textarea’:
case ‘file’: <—

Louie @ Eire Web Design Says:
September 23rd, 2008 at 8:57 am

With this code you can not upload images using ajax. Have a look at Yahoo YUI – http://developer.yahoo.com/yui/

Arun Says:
December 12th, 2008 at 6:51 am

i have php and 3 ajax data in the same form and would like to send all the data into one row in the database

links for 2009-07-20 « Free Open Source Directory Says:
July 21st, 2009 at 2:04 am

[...] Ajax load content from another file using POST or GET | Website Design Ireland, Website Development These is a simple Ajax example that will load content into the page from another file without browser refresh. 05-Oct-2007 – We have updated the javascript to allow the use of forms to be submited using POST. (tags: Ajax load Content from another File using Post or Get | Website Design Ireland, Development) [...]

Henri Says:
September 18th, 2009 at 12:26 pm

Is this great example still holding up with the latest browsers?
And what happend when a user has disabled javascript?

Louie @ Eire Web Design Says:
September 18th, 2009 at 1:40 pm

Yes it does. Cant’see why not.
Adding a submit button sorts out the “JavaScript” disabled issues

Henri Says:
September 19th, 2009 at 12:28 am

Thanks Louie.

I don’t need the form bit, so I shortened the examples somewhat.
But know the loading image is displayed and nothin happens. So I think i cut out to much.
This is all new to me so would you check my code?

[CODE REMOVED]

I’m sure it’s something small or stupid, but i’m staring myself dizzy, and just can’t find the problem.

Henri Says:
September 19th, 2009 at 12:34 am

oh, i can’t seem to paste the code in this message.
If it is not to much to ask, you could look at my files on:
http://ibhuman.16th-foor.nl/ajaxtest.php
http://inhuman.16th-foor.nl/includes/ajax_content.php
http://inhuman.16th-foor.nl/scripts/ajax.js

sorry for the trouble.

Louie @ Eire Web Design Says:
September 19th, 2009 at 7:55 am

Can’t seem to be able to access your links above.
Is your sub-domain setup porperly?
Also Javascript has permission issues when used accross sub-domains (e.g. “domain.com” is not the same as “sub-domain.domain.com”

Louie @ Eire Web Design Says:
September 19th, 2009 at 8:03 am

I removed the code inserted into the “comment” as it contained your server path which should be the domain URL PATH.

You are trying to set this up on a sub-domain, so would you not be better just check on a new page in the main domain folder until you get it working?

Have a look at the example available and just because you don’t need certain Javascript code, it doesn’t mean the other code doesn’t need it either.
Those are functions and they could be called from inside the other ones so leave it as it is until working then clean up what you thing you don’t need.

Example Page: http://www.eire-webdesign.ie/ajax_samples/

Henri Says:
September 19th, 2009 at 1:53 pm

You are right about the sub-domain, in my case they are not properly setup by my hosting provider, so i moved the files to the main domain folder.

First I tried it with all the example code, but it did not work.
So i again stripped it to the bare necessities but it’s still not working.

The right URLs this time are
http://www.16th-floor.nl/ajaxtest.html
and
http://www.16th-floor.nl/ajaxcontent.html
(I know this extension should php but then you wouldn’t be able to read the code,
so there is a identical ajaxcontent.php and ajaxcontent.html.)

I must say I really do appreciate your quick help on an article almost 1 year old,
so i hope you haven’t lost your patience with me yet ;)

Louie @ Eire Web Design Says:
September 19th, 2009 at 2:46 pm

your server returns 500 error

GET http://www.16th-floor.nl/ajaxcontent.php?data=1 500 Internal Server Error 172ms

Henri Says:
September 19th, 2009 at 4:09 pm

pffft, I’ve got it.
As i expected a typo in my code.
Just before the second $_get in line:
if(isset($_GET[‘data’]) && $_GET[‘data’] != “”){
I typed a “(” for some reason.
Anyway, it works :) Expect I’ll be using this example of yours many times know I understand it :)

Thanks for all the help Louie :)

Louie @ Eire Web Design Says:
September 19th, 2009 at 5:02 pm

When testing AJAX, use Firefox browser and install “Firebug” add-on.

http://getfirebug.com/

  • Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Links...

Chicklets...
  • http://www.eire-webdesign.ie/blog/feed/
    http://www.eire-webdesign.ie/blog/feed/
    Google Reader or Homepage
    Add to My Yahoo!
    Subscribe with Bloglines
    Subscribe in NewsGator Online
    add to msn
    Add to My AOL
    Add to Technorati Favorites!
    pageflakes
    windows live