Ajax Implementation

Post custom hacks and enhancements for phpwcms here only. Maybe some of these things will be included in official release later.
Post Reply
betabi
Posts: 26
Joined: Thu 23. Jun 2005, 17:28
Location: Hamburg
Contact:

Ajax Implementation

Post by betabi »

Updated!!!
What is it good for?
I looked for a solution to display article content within the article list view dynamicly – end ended up with implementing ajax.
Let’s say: You have category containing serveral articles which will be displayed as an article list – each article just with it’s header information and a "more"-link. This workaround enables You to show the full article content of the choosen article below/next to the list instead of reloading the whole page just displaying the specified article.

Updated!!!
Example: http://www.andreasgehlen.com/index.php?aid=25
(Click on the thumbnails in the right colum to see it working)

What do You need?
1. The http request:
This workaround uses some code distributed by yahoo. You can get it at:
http://sourceforge.net/project/download ... 2.2.0a.zip
We will just need 2 scripts: "yahoo-min.js" and "connection-min.js". Copy them to Your phpwcms installation -> "template/inc_js"

2. Creating the XML
We need 2 files: "ajax_create.php" and "ajax.php". Create them on the root level of Your installtion.

"ajax_create.php" should look like this:

Code: Select all

<?php
header("Content-Type:text/xml");
$url = 'http://'.$_SERVER['SERVER_NAME'].trim($_SERVER['PHP_SELF'], "ajax_crate.php").'ajax.php?'.getenv('QUERY_STRING');
function getResource($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
}
$feed = getResource($url);
echo $feed;
?>
"ajax.php" is just a stripped off version of the original "index.php":

Code: Select all

<?php

// define some general vars
$content 			= array();
$phpwcms 			= array();
$BL					= array();

// load general configuration
require_once ('config/phpwcms/conf.inc.php');
require_once ('include/inc_lib/default.inc.php');
require_once (PHPWCMS_ROOT.'/include/inc_lib/dbcon.inc.php');


// some initial actions
cleanupPOSTandGET();
define('FE_CURRENT_URL', PHPWCMS_URL . 'index.php' . buildGlobalGET('getQuery'));


ob_start(); //without Compression (or use browsers default)
require_once (PHPWCMS_ROOT.'/config/phpwcms/conf.template_default.inc.php');
require_once (PHPWCMS_ROOT.'/config/phpwcms/conf.indexpage.inc.php');
require_once (PHPWCMS_ROOT.'/include/inc_lib/general.inc.php');
require_once (PHPWCMS_ROOT.'/include/inc_front/cnt.lang.inc.php');
require_once (PHPWCMS_ROOT.'/include/inc_lib/article.contenttype.inc.php');
require_once (PHPWCMS_ROOT.'/include/inc_lib/imagick.convert.inc.php');
require_once (PHPWCMS_ROOT.'/include/inc_front/front.func.inc.php');
require_once (PHPWCMS_ROOT.'/include/inc_front/ext.func.inc.php');
require_once (PHPWCMS_ROOT.'/include/inc_front/content.func.inc.php');

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//predefine values

$content['cat']					= '';
$content['metakey']				= '';
$content['struct']				= get_struct_data(); //reads the complete structure as array
$content['article_date']		= time();
$content['redirect']			= array('code' => '');
$content['all_keywords']		= '';
$content['globalRT']			= array();
$pagelayout						= array();
$no_content_for_this_page		= 0;
$alias							= '';
$_ACCESS_ALLOWED				= true;

//method to get the right action values
//if there is only the ?alias try to find the right category
if(isset($_GET["id"])) {

	$aktion = explode(',', $_GET["id"], 6);
	$aktion[0] = isset($aktion[0]) ? intval($aktion[0]) : 0;
	$aktion[1] = isset($aktion[1]) ? intval($aktion[1]) : 0;
	$aktion[2] = isset($aktion[2]) ? intval($aktion[2]) : 0;
	$aktion[3] = isset($aktion[3]) ? intval($aktion[3]) : 1;
	$aktion[4] = isset($aktion[4]) ? intval($aktion[4]) : 0;
	$aktion[5] = isset($aktion[5]) ? intval($aktion[5]) : 0;
	

} elseif(isset($_GET['aid'])) {
	// try to find correct structure
	$aktion = array(0,0,0,0,1,0);
	$_GET['aid'] = intval($_GET['aid']);
	if($_GET['aid']) {
		$sql  =	"SELECT article_cid FROM ".DB_PREPEND."phpwcms_article WHERE article_id=".$_GET['aid']." LIMIT 1";
		if($result = mysql_query($sql, $db)) {
			if($row = mysql_fetch_row($result)) {
				$aktion[0] = $row[0];
				$aktion[1] = $_GET['aid'];
			}
			mysql_free_result($result);
		}
	}

} else {
	// check the alias
	$aktion = array(0,0,0,1,0,0);

	if(count($GLOBALS['_getVar'])) {
		reset($GLOBALS['_getVar']);
		$alias = trim(key($GLOBALS['_getVar']));
		if($alias && !strpos($alias, '=')) { // check alias for "=" what means no alias
			$sql = "SELECT acat_id FROM ".DB_PREPEND."phpwcms_articlecat WHERE acat_trash=0 AND acat_alias='".aporeplace($alias)."' LIMIT 1";
			if($result = mysql_query($sql, $db)) {
				if($row = mysql_fetch_row($result)) {
					$aktion[0] = $row[0];
				}
				mysql_free_result($result);
			}
		}
	}
}




//define the current article category ID
$content["cat_id"]	 = $aktion[0];
$aktion[4] = 1;

include_once(PHPWCMS_ROOT."/include/inc_front/content.article.inc.php");
// create xml
echo ("<?xml version=\"1.0\" encoding=\"UTF-8\"?><list><item><![CDATA[");
echo ($content["main"]);
echo ($content['CB']['RIGHT']);
echo ($content['CB']['LEFT']);
echo ($content['CB']['FOOTER']);
echo ("]]></item></list>");

///////////////////////////////////////////////////////////////////////////////////////////////////////////
// send buffer to browser
ob_end_flush();
?>
Look at the last several lines of "ajax.php". This is where the xml is created:

Code: Select all

echo ("<?xml version=\"1.0\" encoding=\"UTF-8\"?><list><item><![CDATA[");
echo ($content["main"]);
echo ($content['CB']['RIGHT']);
echo ($content['CB']['LEFT']);
echo ($content['CB']['FOOTER']);
echo ("]]></item></list>");
Here You might wish to add some HTML formating to the different content blocks...

3. Parsing the XML and calling Ajax
You have to add 3 small functions to "frontend.js":

Code: Select all

function getModuleHtml(sUrl){ 
	// replace "index.php" -> "ajax_create"
	sUrl = "ajax_create" + sUrl.substr(5);
	// just display a short "Loading message"
	document.getElementById('ajax_output').innerHTML = "Loading Content...";
         // Initiate the HTTP GET request.
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success:successHandlerHtml, failure:failureHandler });
}
// This puts out the XML to Your page. Make sure that there is an element with the id="ajax_output". This is where the content will go to...
function successHandlerHtml(o){ 
	var ie = false;
	var root = o.responseXML.documentElement;
	var array_all = root.getElementsByTagName('item');
	// cdata section ausgeben
	if (!array_all[0].childNodes[1]) {
		ie = true;
	}
	if (ie == true) {
		document.getElementById('ajax_output').innerHTML = array_all[0].childNodes[0].nodeValue;
	}
	else {
		document.getElementById('ajax_output').innerHTML = array_all[0].childNodes[1].nodeValue;
	}
}
// This is a simple failure handler
function failureHandler(o){ 
	document.getElementById('ajax_output').innerHTML = o.status + " " + o.statusText; 
}
How to use it?
1. Make sure You have created the necessary files and added the Javascript functions.
2. Add a container for the dynamic content to your template like: "<div id="ajax_output">Ajaxoutput</div>"
3. Include the Yahoo functions by pasting

Code: Select all

<script src="template/inc_js/yahoo-min.js" type="text/javascript"></script>
<script src="template/inc_js/connection-min.js" type="text/javascript"></script>
to the header part of Your template.
3. Add the "Ajax call" to Your "article_summary_list.tmpl": Just replace the "[MORE]-part" with:

Code: Select all

[MORE]<div class="phpwcmsArticleListMore"><a href="javascript:getModuleHtml('{ARTICLELINK}')">display</a></div>[/MORE]
4. That is all.
Last edited by betabi on Sun 29. Apr 2007, 20:38, edited 4 times in total.
User avatar
nekket
Posts: 613
Joined: Tue 18. Nov 2003, 15:46
Location: Baden-Baden
Contact:

Post by nekket »

where can i see it in action? :D
pixelpublic GmbH | Agentur für Neue Medien und Gestaltung
Ati
Posts: 50
Joined: Fri 19. May 2006, 20:09
Contact:

Post by Ati »

Yeah that would be nice...
"Seien wir realistisch - versuchen wir das Unmögliche" (Chè Guevara)
silencox
Posts: 11
Joined: Wed 11. Oct 2006, 10:38

Post by silencox »

nekket wrote:where can i see it in action? :D
You have link on top of his post

http://www.andreasgehlen.com/index.php?ajaxtest
phalancs
Posts: 793
Joined: Thu 19. Feb 2004, 05:09
Location: Germany

Post by phalancs »

to show the full article content of the choosen article below/next to the list instead of reloading the whole page
Hmm, on your ajaxtestpage, if I click on a link, the list disappears. Did I get you wrong, is there something else you meant?
2008
Post Reply