Closed Thread
Results 1 to 8 of 8

Thread: Don't be scared of AJAX :)

  1. #1
    stop staring krakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to behold krakjoe's Avatar
    Join Date
    May 2006
    Location
    UK
    Posts
    3,616

    Lightbulb Don't be scared of AJAX :)

    If you're like me at all, then you've probably looked into integratin ajax into your applications or scripts and gotten scared off by things like prototype.js or, scared off by thinking ajax is a totally new language.

    In actual fact it's incredibly easy to utilize ajax without the use of external libraries using real easy javascript in conjuncton with some even more basic php code.

    I wrote the following to show someone on another forum how exactly to use ajax on pages to do whatever you want, hopefully someone here can find it usefull also.

    Filename : index.html ( or php doesn't matter )

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Ajax Usage Example</title>
    <!-- This next part is javascript, you can put this in a seperate file, or not, it's up to you -->
    <script language="javascript">
    function processAjax(ElementId, AjaxProcess, Input)
    {
    	xmlHttp=GetXmlHttpObject() // Create xmlHTTP Object
    	/**
    	* This switch controls what the xmlHTTP object is doing
    	* it's probably not needed for your use, but it's not a 
    	* bad way of doing things, so take note of how it works
    	**/
    	switch(AjaxProcess)
    	{ // Begin : switch(AjaxProcess);
    		/**
    		* Form Process
    		**/
    		case 'FormsExample':
    		var url="AjaxProcess.php" // Begin to build the url to the proccessing script
    		url=url+"?process=forms&name="+ encodeURI( document.getElementById(Input).value )
    		url=url+"&sid="+Math.random()
    		xmlHttp.onreadystatechange=StateChangedForms // Discover state changes
    		break;
    		/**
    		* Content Process
    		**/
    		case 'ContentExample':
    		var url="AjaxProcess.php" // Begin to build the url to the proccessing script
    		url=url+"?process=content&input="+Input
    		url=url+"&sid="+Math.random()
    		xmlHttp.onreadystatechange=StateChangedContent // Discover state changes
    		break;
    	} // End : switch(AjaxProcess);
    	xmlHttp.open("GET",url,true) // Open object at the url specified
    	xmlHttp.send(null) // Send the AJAX request
    }
    /**
    * Detecting if a state has changed ( FORMS EXAMPLE )
    **/
    function StateChangedForms() 
    { 
    	//document.write(ElementId);
    	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    	{ 
    	document.getElementById('exampleForm').innerHTML=xmlHttp.responseText 
    	}
    } 
    /**
    * Detecting if a state has changed ( CONTENT EXAMPLE )
    **/
    function StateChangedContent() 
    { 
    	//document.write(ElementId);
    	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    	{ 
    	document.getElementById('exampleContent').innerHTML=xmlHttp.responseText 
    	}
    }
    /**
    * This function calls an xmlHTTP object for use to do whatever....
    **/
    function GetXmlHttpObject()
    { 
    var objXMLHttp=null
    	if (window.XMLHttpRequest)
    	{
    		objXMLHttp=new XMLHttpRequest()
    	}
    	else if (window.ActiveXObject)
    	{
    	objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
    	}
    return objXMLHttp
    } 
    </script>
    </head>
    
    <body>
    <h2>Forms usage</h2>
    Enter your name in the box, if your name is joe, you'll be congragtulated : 
    <!-- You'll notice in the form below there is an id tag, this is needed on most elements -->
    <input type="text" id="name" 
    onkeyup="javascript: processAjax('examlpeForm', 'FormsExample', 'name');" 
    name="name" />
    <br />
    <span id="exampleForm"></span>
    <h2>Content Usage</h2>
    <div >
    Click the links below to swap dynamic content<br />
    <a href="javascript: processAjax('exampleContent', 'ContentExample', 1);">Show Content 1</a>&nbsp;&nbsp;
    <a href="javascript: processAjax('exampleContent', 'ContentExample', 2);">Show Content 2</a></div>
    <span id="exampleContent"></span>
    </body>
    </html>
    Filename : AjaxProcess.php (exactly like that)

    PHP Code:
    <?
    switch ($_GET['process'])
    {
        case 
    "forms":
        if ( 
    strlen($_GET['name']) > )
        {
            if (
    $_GET['name'] == "Joe" || $_GET['name'] == "joe")
            {
                
    $responseText "Yay, congratulations, you're me";
            }
            else {
                    
    $responseText "You'll never be me ";
                 }
        }
        break;
        
        case 
    "content":
        switch(
    $_GET['input'])
        {
            case 
    1:
            
    $responseText "Content 1 I could be anything";
            break;
            
            case 
    2:
            
    $responseText "Content 2 I could be anything";
            break;
        }
        break;
    }

    echo 
    $responseText;
    ?>
    DEMO : http://ex.krakjoe.info/AjaxExample/example.html

    The above effects can be achieved without the use of ajax entirely, all it gives you is dynamic content instead of static js vars.

    NOTE : Please note, the above php is not necessarily secure, nor is it meant to be, it's meant to be simple, remember that!!
    Last edited by krakjoe; December 4th, 2006 at 10:50.
    (\__/) Joe Watkins
    (='.'=) Software Architect
    (")_(") http://pthreads.org
    Copy and paste bunny into your sig, help him gain world domination.

  2. #2
    FWS Addict Paul White is an unknown quantity at this point Paul White's Avatar
    Join Date
    Aug 2005
    Location
    Over the damn rainbow...
    Posts
    569
    Thanks Joe! That was really helpful along with another simple script that I have seen just like that. I have never really wanted to attempt it since it is presented as very confusing. Just one question: Can you process multiple form items with AJAX, and if so, how?

    Thanks!

  3. #3
    stop staring krakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to behold krakjoe's Avatar
    Join Date
    May 2006
    Location
    UK
    Posts
    3,616
    sure, where it says :
    Code:
    var url="AjaxProcess.php" // Begin to build the url to the proccessing script
    		url=url+"?process=forms&name="+ encodeURI( document.getElementById(Input).value )
    		url=url+"&sid="+Math.random()
    for example, just keep building the url in that fassion

    Code:
    var url="AjaxProcess.php" // Begin to build the url to the proccessing script
    url=url+"?process=forms&name="+ encodeURI( document.getElementById(Input).value )
    url=url+"$newvar="+ encodeURI( document.getElementById(InputNexr).value )
    url=url+"&sid="+Math.random()
    Like so, you'd need to change the html slightly, so the the ajax process was executed onsubmit instead of onkeyup or onclick, but is pretty easy....also, instead of using js vars, just give the form elements ids accordingly....

    Glad it helped someone....
    (\__/) Joe Watkins
    (='.'=) Software Architect
    (")_(") http://pthreads.org
    Copy and paste bunny into your sig, help him gain world domination.

  4. #4
    Larger than life Richard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to behold
    Join Date
    Feb 2006
    Location
    England
    Posts
    4,131
    AJAX is amazing, I was experimenting with it quite awhile ago and i've just updated some of my work to show you:

    This is an AJAX Gallery System

    index.html (Most of the HTML in this is not needed...)
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>::Richard Anderson::Ajax Gallery::</title>
    <style>
    <!--
    body         { font-family: Tahoma; font-size: 8pt; text-decoration: none; padding: 3px }
    td           { font-family: Tahoma; text-decoration: none; padding: 0 }
    .imgFader{ position:relative; filter:alpha(opacity=0); -moz-opacity:0.0 }
    .title {
        padding:3px; COLOR: #5E5E5E;
        FONT-SIZE: 8pt;
        FONT-FAMILY: Trebuchet MS
    }
    .title a {
        padding:3px; COLOR: #808080;
        FONT-SIZE: 8pt;
        FONT-FAMILY: Trebuchet MS; text-decoration:none; font-weight:bold
    }
    .title a:hover {
        padding:3px; COLOR: #333333;
        FONT-SIZE: 8pt;
        FONT-FAMILY: Trebuchet MS; text-decoration:none; font-weight:bold
    }
    .text           { font-family: Tahoma; text-decoration: none; padding: 0; font-size:8pt }
    .style5 {	font-family: Tahoma;
    	font-size: 12px;
    }
    .style5 {font-size: 10pt}
    .style6 {	font-family: Tahoma;
    	font-size: 12px;
    	margin-left: 5px;
    }
    .style6 {font-size: 10pt;}
    .nav {font-size: 10pt;
    	color:#000000;
    	font-weight: bold;
    	border-bottom:0px;
    	border-top:0px;
    }
    .style7 {font-size: 10pt; color: #FF3300; font-weight: bold; }
    -->
    </style>
    <script language = "javascript">
    var theusername = "";
    var XMLHttpRequestObject = false;
    
    if (window.XMLHttpRequest) {
    	XMLHttpRequestObject = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
    	XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
    }
    function getData(dataSource, divID)
    {
    	if(XMLHttpRequestObject) {
    		var obj = document.getElementById(divID);
    		XMLHttpRequestObject.open("GET", dataSource);
    		XMLHttpRequestObject.onreadystatechange = function()
    		{
    			if (XMLHttpRequestObject.readyState == 4 &&
    			XMLHttpRequestObject.status == 200) {
    			obj.innerHTML = XMLHttpRequestObject.responseText;
    			}
    		}
    		XMLHttpRequestObject.send(null);
    	}
    }
    function getimage(id)
    {
    	document.getElementById('addnew').style.display = "none";
    	document.getElementById('gall-tab').style.display = "";
    	document.getElementById('gallery').innerHTML = "<img src='images/working.gif' alt='Loading Data' /> Loading...";
    	var data = id;
    	if (id == 0) {
    		var data = "";
    	}
    	getData('images.php?id=' + data, 'gallery');
    }
    function addimage(thelink)
    {
    	document.getElementById('addnew').style.display = "none";
    	document.getElementById('gall-tab').style.display = "";
    	document.getElementById('gallery').innerHTML = "<img src='images/working.gif' alt='Loading Data' /> Loading...";
    	getData('images.php?add=' + document.form1.textfield.value, 'gallery');
    }
    function addnewimage()
    {
    	document.getElementById('addnew').style.display = "";
    	document.getElementById('gall-tab').style.display = "none";
    }
    </script>
    </head>
    
    <body onload="getimage('0');">
    <table width="60%" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td bgcolor="#b72e33" height="11"><img src="images/space.gif" border="0" height="11" width="11" /></td>
      </tr>
      <tr>
        <td height="41" valign="top"><a href="index.php"><img src="images/header.gif" border="0" height="41" width="458" /></a>
      </tr>
    
    </table>
    <table width="60%" border="0" align="center" cellpadding="0" cellspacing="0">
    
      <tr valign="top">
        <td width="65%"><div id="gall-tab" style="display:inline">
    	<br /><br />
            <table id="table5" border="1" bordercolor="#5e5e5e" cellpadding="0" width="100%">
            <tbody>
              <tr>
                <td style="padding: 3px 5px;" class="title" bgcolor="#d9d9d9">&raquo; My Ajax Gallery </td>
              </tr>
              <tr>
                <td align="center">
    <div id="gallery">
    </div>
    </td>
              </tr>
              <tr>
                <td style="padding: 3px 5px;" class="title" bgcolor="#d9d9d9"><div align="right"><a href="#" onclick="getimage('0');return false;">View All Images</a> <a href="#" onclick="addnewimage();return false;">Add New Image</div></td>
              </tr>
            </tbody>
          </table>     
          <br /><br /></div>
          <div id="addnew" style="display:none"><table id="table5" border="1" bordercolor="#5e5e5e" cellpadding="0" width="100%">
            <tbody>
              <tr>
                <td style="padding: 3px 5px;" class="title" bgcolor="#d9d9d9">&raquo; Add An Image to Above </td>
              </tr>
              <tr>
                <td align="center"><div id="form">
                  <form id="form1" name="form1" method="post" action="">
                    <br />URL: <input type="text" name="textfield" /> &nbsp; &nbsp;
    				 <input name="button" type="button" value="Add" onclick="addimage('textfield.value')" />
    				<br />
    				<br />
                  </form>
                  </div></td>
              </tr>
              <tr>
                <td style="padding: 3px 5px;" class="title" bgcolor="#d9d9d9"><div align="right"><a href="#" onclick="getimage('0');return false;">View All Images</a></div></td>
              </tr>
            </tbody>
          </table></div>
        <p>&nbsp; </p></td>
        <td width="35%">Nav Bar here?</td>
      </tr>
    </table>
    <table width="60%" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td bgcolor="#b72e33" height="11"><img src="images/space.gif" border="0" height="11" width="11" /></td>
      </tr>
    </table>
    </body>
    </html>
    images.php
    Code:
    <?php
    if ((isset($_GET['id'])) && ($_GET['id'] != ""))
    {
    	$downloads = parse_ini_file("images.txt", true);
    	foreach($downloads as $name => $data)
    	{
    		if ($data['id'] == $_GET['id'])
    		{
    			echo "<table width='100%' border='0' cellspacing='5' cellpadding='2'>\n<tr><td align='center'>";
    			echo "<a href=\"#\" onclick=\"getimage('0');return false;\">" . "<img src='".$data['link']."'>" . "</a>";
    			echo "</td></table>";
    		}
    	}
    } else {
    if ((isset($_GET['add'])) && ($_GET['add'] != ""))
    {
    	$error = "";
    	if (@!getimagesize($_GET['add']))
    	{
    		$error = "Not a Valid Image! It was NOT added!";
    	}
    	$id = 1;
    	$downloads = parse_ini_file("images.txt", true);
    	foreach($downloads as $name => $data)
    	{
    		$id = $id + 1;
    		if ($data['link'] == $_GET['add'])
    		{
    			$error = "That image has already been added!";
    		}
    	}
    	if ($error == "") {
    	$file = fopen("images.txt", "a");
    	$data = "[image {$id}]\nid={$id}\nlink=\"".$_GET['add']."\"\n\n";
    	fwrite($file, $data);
    	fclose($file);
    	}
    }
    $sep = "</tr>\n<tr align='center'>\n";
    $before = "<td>";
    $after = "</td>";
    $downloads = parse_ini_file("images.txt", true);
    $num = 0;
    echo "<table width='100%' border='0' cellspacing='5' cellpadding='2'>\n<tr align='center'>";
    if ($error != "")
    {
    	echo "<td align='center' colspan='3'>{$error}</td>" . $sep;
    }
    foreach($downloads as $name => $data)
    {
    	if ($num == 3)
    	{
    		$num = 0;
    		echo $sep;
    	}
    	echo $before . "<a href=\"#\" onclick=\"getimage('".$data['id']."');return false;\">";
    	echo "<img src='".$data['link']."' width='80' height='100'><br />";
    	$blah = getimagesize($data['link']);
    	echo $blah[1] . "x" . $blah[0];
    	echo $after . "</a>";
    	$num = $num + 1;
    }
    echo "</tr>\n</table>";
    }
    ?>
    DEMO: http://santext.net/
    Quote Originally Posted by PHPRalph View Post
    Greetings?!?!
    Condign got to this part and am looking saucy to chilling gone from concluded here and hainging with all

  5. #5
    stop staring krakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to behold krakjoe's Avatar
    Join Date
    May 2006
    Location
    UK
    Posts
    3,616
    ^^Nice....
    (\__/) Joe Watkins
    (='.'=) Software Architect
    (")_(") http://pthreads.org
    Copy and paste bunny into your sig, help him gain world domination.

  6. #6
    Larger than life Richard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to beholdRichard is a splendid one to behold
    Join Date
    Feb 2006
    Location
    England
    Posts
    4,131
    Quote Originally Posted by KRAK_JOE View Post
    ^^Nice....
    Blah. I used a flat file system as I could not be bothered to use mySQL It's nothing special and took all of less than an hour to code, but then again, I do know PHP and Javascript very well
    Quote Originally Posted by PHPRalph View Post
    Greetings?!?!
    Condign got to this part and am looking saucy to chilling gone from concluded here and hainging with all

  7. #7
    FWS Addict Paul White is an unknown quantity at this point Paul White's Avatar
    Join Date
    Aug 2005
    Location
    Over the damn rainbow...
    Posts
    569
    Thanks Joe, that was a huge help! Do you mind if I use some of that with the TUGGO (my open source cms) source code eventually? I would be happy to give a link to your website in the code and on the credits page that is included with every release!

  8. #8
    stop staring krakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to beholdkrakjoe is a splendid one to behold krakjoe's Avatar
    Join Date
    May 2006
    Location
    UK
    Posts
    3,616
    Of course
    (\__/) Joe Watkins
    (='.'=) Software Architect
    (")_(") http://pthreads.org
    Copy and paste bunny into your sig, help him gain world domination.

Closed Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts