PRAjax PHP Reflected Ajax Developer Manual

Similar documents
User Interaction: jquery

10.1 Overview of Ajax

Web UI. Survey of Front End Technologies. Web Challenges and Constraints. Desktop and mobile devices. Highly variable runtime environment

Computer Science E-1. Understanding Computers and the Internet. Lecture 10: Website Development Wednesday, 29 November 2006

Manual Html A Href Onclick Submit Form

Anatomy of an HTML document

Session 18. jquery - Ajax. Reference. Tutorials. jquery Methods. Session 18 jquery and Ajax 10/31/ Robert Kelly,

GWT - CREATE APPLICATION

Introduction to WEB PROGRAMMING

Introduction to using HTML to design webpages

CITS1231 Web Technologies. Ajax and Web 2.0 Turning clunky website into interactive mashups

Programmazione Web a.a. 2017/2018 HTML5

In the early days of the Web, designers just had the original 91 HTML tags to work with.

JS Lab 1: (Due Thurs, April 27)

Stamp Builder. Documentation. v1.0.0

Notes General. IS 651: Distributed Systems 1

UNIVERSITY OF TORONTO Faculty of Arts and Science APRIL 2016 EXAMINATIONS. CSC309H1 S Programming on the Web Instructor: Ahmed Shah Mashiyat

Connecting the Dots. Building Web Applications with PHP, HTML, CSS, and JavaScript

Using Development Tools to Examine Webpages

Web Programming Step by Step

jmaki Overview Sang Shin Java Technology Architect Sun Microsystems, Inc.

Web Recruitment Module Customisation

Javascript, Java, Flash, Silverlight, HTML5 (animation, audio/video, ) Ajax (asynchronous Javascript and XML)

University of Washington, CSE 190 M Homework Assignment 9: Remember the Cow (To-Do List)

Hyperlinks, Tables, Forms and Frameworks

TIME SCHEDULE MODULE TOPICS PERIODS. HTML Document Object Model (DOM) and javascript Object Notation (JSON)

Consent Management Platform (CMP) Full Documentation


CS 350 COMPUTER/HUMAN INTERACTION. Lecture 6

HTML Summary. All of the following are containers. Structure. Italics Bold. Line Break. Horizontal Rule. Non-break (hard) space.

Web Security, Summer Term 2012

FUNDAMENTALS OF WEB DESIGN (46)

Web Development and HTML. Shan-Hung Wu CS, NTHU

Web Security, Summer Term 2012

PIC 40A. Midterm 1 Review

Dreamweaver: Portfolio Site

<style type="text/css"> <!-- body {font-family: Verdana, Arial, sans-serif} ***set font family for entire Web page***

Jquery Manually Set Checkbox Checked Or Not

GWT - FORMPANEL WIDGET

The building block of a CSS stylesheet. A rule consists of a selector and a declaration block (one or more declarations).

AngularJS AN INTRODUCTION. Introduction to the AngularJS framework

Asynchronous JavaScript + XML (Ajax)

Chapter4: HTML Table and Script page, HTML5 new forms. Asst. Prof. Dr. Supakit Nootyaskool Information Technology, KMITL

UNIT 3 SECTION 1 Answer the following questions Q.1: What is an editor? editor editor Q.2: What do you understand by a web browser?

Human-Computer Interaction Design

E ECMAScript, 21 elements collection, HTML, 30 31, 31. Index 161

Jquery Ajax Json Php Mysql Data Entry Example

CIS 408 Internet Computing Sunnie Chung

Copyright IBM Corporation All Rights Reserved.

By completing this practical, the students will learn how to accomplish the following tasks:

Lab 1 - Introduction to Angular

READSPEAKER ENTERPRISE HIGHLIGHTING 2.5

Introduction to Web Development

Creating an Online Catalogue Search for CD Collection with AJAX, XML, and PHP Using a Relational Database Server on WAMP/LAMP Server

Uniform Resource Locators (URL)

Unveiling the Basics of CSS and how it relates to the DataFlex Web Framework

Multimedia im Netz Online Multimedia Winter semester 2015/16. Tutorial 07 Minor Subject

The Structure of the Web. Jim and Matthew

LexisNexis Publisher. User Guide. January Page 1

ethnio tm IMPLEMENTATION GUIDE ETHNIO, INC W SUNSET BLVD LOS ANGELES, CA TEL (888) VERSION NO. 3 CREATED JUL 14, 2017

ITNP43: HTML Lecture 4

Controlled Assessment Task. Question 1 - Describe how this HTML code produces the form displayed in the browser.

Configuring Hotspots

Working with Database. Client-server sides AJAX JSON Data formats Working with JSON data Request Response Bytes Database

University of Washington, CSE 190 M Homework Assignment 8: Baby Names

CSS is applied to an existing HTML web document--both working in tandem to display web pages.

Project 3 Web Security Part 1. Outline

AJAX and JSON. Day 8

src1-malan/ajax/ajax1.html ajax1.html Gets stock quote from quote1.php via Ajax, displaying result with alert().

yawrap Documentation Release Michal Kaczmarczyk

Jquery.ajax Call Returns Status Code Of 200 But Fires Jquery Error


CPSC 481: CREATIVE INQUIRY TO WSBF

Working Bootstrap Contact form with PHP and AJAX

Diploma in Digital Applications Unit 5: Coding for the Web

AJAX ASYNCHRONOUS JAVASCRIPT AND XML. Laura Farinetti - DAUIN

JavaScript Specialist v2.0 Exam 1D0-735

How to lay out a web page with CSS

Managing State. Chapter 13


Discovery Service Infrastructure for Test- bädden

Mobile Web Applications. Gary Dubuque IT Research Architect Department of Revenue

WEBSI TE DESIGNING TRAINING

ajax1.html 1/2 lectures/7/src/ ajax1.html 2/2 lectures/7/src/

The Web. Session 4 INST 301 Introduction to Information Science

LING 408/508: Computational Techniques for Linguists. Lecture 14

University of Washington, CSE 154 Homework Assignment 8: Baby Names

Ajax HTML5 Cookies. Sessions 1A and 1B

PHP: Hypertext Preprocessor. A tutorial Introduction

Creating a Job Aid using HTML and CSS

Web Architecture Review Sheet

Stylesheet Fundamentals

DATABASE SYSTEMS. Introduction to web programming. Database Systems Course, 2016

GWT - TOGGLEBUTTON WIDGET

Web Designer s Reference

Wanted! Introduction. Step 1: Styling your poster. Activity Checklist. In this project, you ll learn how to make your own poster.

<body bgcolor=" " fgcolor=" " link=" " vlink=" " alink=" "> These body attributes have now been deprecated, and should not be used in XHTML.

Introduction to Computer Science Web Development

WME and Automatic Mathematical Answer Checking

Cascading Style Sheet. Styles as Tag Attributes. Syntax. <h1>: what font type/size is used? STYLE = SELECTOR {RULES} Attributes such as bgcolor

Transcription:

PRAjax PHP Reflected Ajax Developer Manual

Index PRAjax PHP Reflected Ajax... 1 Index... 2 What is PRAjax?... 3 PRAjax in short... 3 Schematic overview... 4 Introduction... 5 Requirements... 5 Installation... 5 Hello World... 5 Advanced features... 7 Add external client-side script... 7 Alert client-side on server-side... 7 Execute script on client-side on server-side... 7 Check if a page load is an Ajax Call... 7 Set character set other than default UTF-8... 7 Use a different target for specific calls... 7 Use a different transport method than the one provided by PRAjax... 7 Show a busy-message when loading... 8 Show an hourglass pointer when loading... 8 Extra s... 9 Suggest component... 9 UpdatePanel component... 10 About... 12 Page 2 of 12

What is PRAjax? PRAjax in short PRAjax is short for PHP Reflected Ajax. It is a helper class for reflecting PHP code into JavaScript and asynchronous methods and vice-versa. The most significant features of PRAjax are: Allows easier Ajax programming with PHP PHP functions and objects can be reflected to JavaScript PHP objects can be used in JavaScript, both properties and (registered) functions PRAjax creates all wrappers for the developer Automatic conversion of return values and parameters between PHP and JavaScript Transparent client-side and server-side interaction Page 3 of 12

Schematic overview In order to fully understand how PRAjax passes a call between client-side and server-side, it can be useful to see a visualised flow of a PRAjax call. Below, you ll find a schematic overview of a simple HelloWorld call: PRAjax call flow PHP server-side PRAjax layer JavaScript client-side Register function for use in JS function HelloWorld() Register function HelloWorld() Wrapper function for HelloWorld() This looks like: function HelloWorld () { prajax_call("helloworld", HelloWorld.arguments); Execute a PHP function from JavaScript Dispatch JSON request to PHP function HelloWorld() (done by HandleClientRequ est()) Create XML request Wait for result... Call HelloWorld(Hello World_cb) function HelloWorld() Receive result and dispatch to JavaScript This looks like: function HelloWorld_cb (data) { alert(data); function HelloWorld_cb(data) Page 4 of 12

Introduction Requirements To use PRAjax, the following components are required on server-side: HTTP web server supporting PHP PHP version 4.1 or higher Optional PEAR module Services_JSON (included with PRAjax when you do not have PEAR components installed) 100kB free webspace for the PRAjax libraries Installation Installation of PRAjax is simple. Basically, copy all files from the /bin folder of the PRAjax download to your webserver, eventually in a subfolder, and PRAjax is up and running. Hello World As a basic example, we ll create a simple Hello World example. It will display a button on client-side, and call a server-side function HelloWorld. Results of that function will be displayed in a JavaScript alert on client-side: First of all, include PRAjax.php in your script, and instantiate it: // Use bin or src? $strsources = '../bin'; // Import PRAjax require_once($strsources. '/PRAjax.php'); // Instantiate PRAjax $objprajax = new PRAjax($strSources. '/'); After that, register the PHP function names yyou want to be able to call from JavaScript: // Register functions $objprajax->registerfunction('helloworld'); Optionally, you can show a wait cursor when server-side code is being executed: $objprajax->showwaitcursor(); Very important: handle client requests, preferably after registering objects and functions for PRAjax: // Handle PRAjax client request $objprajax->handleclientrequest(); And finally, our server-side function HelloWorld which we registered through PRAjax: // Functions function HelloWorld() { return "Hello World! ". date("y/m/d H:i:s"); Page 5 of 12

Now we can start writing our client-side code. Important thing is to include the PRAjax JavaScript code by using <?php $objprajax->getjavascript();?> in your page head tag. Also, add your callback functions. A callback function is a function that receives the server s output and can process it. In our HelloWorld-case, we want to alert() a message from the server. <html> <head> <title>hello World</title> <?php $objprajax->getjavascript();?> <script language="javascript"> <!-- // Callback functions function HelloWorld_cb(data) { alert(data); // --> </script> </head> <body> <form name="frmform"> <h1>hello World</h1> <input type="button" value="hello World" onclick="helloworld(helloworld_cb);"> </form> </body> </html> Make sure that when you call your server-side function, the last argument MUST be a callback function. If you do not want a callback, use an empty function (PRAjax.Nothing), or let PRAjax fix this automatically. Take a look at the provided examples in the distribution. These cover most aspects and features of PRAjax development. Examples can be found in the /examples folder. Page 6 of 12

Advanced features Add external client-side script When you want to load an external JavaScript file on your PRAjax-enabled webpage, you might want to use one of the following functions: Client-side: PRAjax.AddScript( file.js ); Server-side: $objprajax->addscript( file.js ); Note that the script path passed to PRAjax is relative to the path your webpage resides on. Alert client-side on server-side On the server-side, you can issue an alert() on client-side. Use the following code: $objprajax- >Alert( This is an alert! ); Execute script on client-side on server-side If you want to perform a client-side script from server-side, this can be done using $objprajax- >ExecuteScript( document.write( test ); );. This can be useful if you want to hide a DOM element or something. Adviced is not to use this too much, to keep server and client code separated. Check if a page load is an Ajax Call When you want to know if a page load is an Ajax call, and not a simple HTTP request, check the function, $objprajax->isajaxcall() which returns true/false. Set character set other than default UTF-8 Some people use different character sets than UTF-8. PRAjax uses UTF-8 by default, but be sure to add the necessary header in your HTTP response. All pages using PRAjax should output header("content-type: text/html; charset=utf-8"); When you want to use a different character set, make sure you output the right header, for example header("content-type: text/html; charset=iso-8859-1");, and that you inform PRAjax to use that character set, for example $objprajax->setcharset( ISO-8859-1 ); Use a different target for specific calls Sometimes, it can be usefull to fire a PRAjax call to another script than the originating one. For example, a news ticker updating every few seconds, can benefit from getting its data from another page. This way, the same script can be used on multiple pages showing the news ticker. Performing a call on another script is easy, and can be done per-function on the client-side: <input type="button" value="simple Hello World" onclick="helloworld(helloworld_cb, 'setprajaxtarget:example_helloworld.php;');"> This code calls the HelloWorld() function registered in example_helloworld.php. Make sure you register the function HelloWorld() in your originating page AND in your target page. Browse the examples folder for a concrete example of an external call. Use a different transport method than the one provided by PRAjax Some people use prototype.js or other, similar JavaScript libraries providing XMLHttpRequest transfers. PRAjax uses its own transport, but can also use other transports, for example the one provided by prototype.js. PRAjax does not load its own transport to the client when you want to do that, saving a few bytes in download size for each visitor of your website. If you want to use another transport, make sure you inform PRAjax about that on the server-side: $objprajax->setuseprajaxtransport(false); Afterwards, you should create a wrapper for the 3rd-party transport. Here s a wrapper example for prototype.js: // Custom transport class, must implement Page 7 of 12

// PerformRequest(uri, post_data, callbackfunction, // errorfunction, opencallcount) function CustomTransport () { CustomTransport.prototype.PerformRequest = function (uri, post_data, callbackfunction, errorfunction, opencallcount) { var ajax = new Ajax.Request(uri, {method: 'post', parameters: post_data, onsuccess: function (xmlobj) { callbackfunction(xmlobj.responsetext);, onfailure: errorfunction ); You should also override a PRAjax method, namely PRAjax.CreateTransfer. This is necessary to use your wrapper function: // Transport factory PRAjax.CreateTransfer = function () { return new CustomTransport(); Show a busy-message when loading When busy performing a PRAjax request, PRAjax can automatically show a message on client-side, informing that a request is being made. An example of how this looks: An effect like that can be achieved by passing PRAjax the right information on server side: $objprajax->showbusymessage(true, <img src= busy.gif > Busy, prajax_status ); The first parameter is a boolean, which is true/false if you want to show the busy message. The second parameter is a string containing the message to show when PRAjax is performing a request. This can be plain text, but also HTML code. Be sure to escape te right characters! The third parameter contains the DOM element id of an element in which the preceding message should be shown. This is most likely a DIV that you place somewhere on your web page. Show an hourglass pointer when loading In addition to the busy message, you can also show an hourglass pointer when PRAjax is working. Use $objprajax->showwaitcursor(true); on server-side to display the hourglass pointer. Page 8 of 12

Extra s Suggest component Google first introduced Google suggest a while ago. This feature uses a dropdown list when typing, filling its list contents dependent on the value entered. PRAjax provides a component similar to that, using a PRAjax call for getting its data. Here is how it looks: A suggest field can easily be added to your website. Find some example code underneath. The most important thing is that you have a server-side function which returns an array of values, in the example this is called SuggestYear. PRAjax will then automatically use that array as data source. In the following code, necessary items for using the suggest component are printed in bold. <?php // Set the header header("content-type: text/html; charset=utf-8"); // Use bin or src? $strsources = '../bin'; // Import PRAjax require_once($strsources. '/PRAjax.php'); // Instantiate PRAjax $objprajax = new PRAjax($strSources. '/'); // Functions function SuggestYear($pValue) { $aarray = array(); for ($i = date('y'); $i >= 1900; $i--) { if (substr($i, 0, strlen($pvalue)) == $pvalue) { array_push($aarray, $i); return $aarray; // Register functions $objprajax->registerfunction('suggestyear'); // Handle PRAjax client request $objprajax->handleclientrequest();?> <html> <head> <title>auto-suggest</title> <?php $objprajax->getjavascript();?> Page 9 of 12

<script language="javascript" src="../src/prajax_component_suggest.js"></script> <style type="text/css" media="all"> @import "../src/prajax_component_suggest.css"; </style> </head> <body> <form name="frmform" style="font-family: Arial, Helvetica, sans-serif; fontsize: 11px;"> Your birth year:<br> <input type="text" name="txtbirthyear" id="txtbirthyear" prajax_suggest="suggestyear" style="width: 150px;"><br> </form> </body> </html> UpdatePanel component Some people already know Atlas. Atlas is an ASP.NET based Ajax framework, which introduced partial page rendering without much effort. PRAjax also supports this. The principle is easy: Add the attribute prajax_updatepanelform="true" to forms you want to submit using PRAjax Add the attribute prajax_updatepanel="true" to DIV elements you want to update after form submission PRAjax will then automatically hook itself into your page. When a form is submitted, PRAjax will render the page as normal, and return only updated DIV elements containing modified contents. This way, PRAjax enables much smaller downloads than an initial page load. In the following code, necessary items for using the UpdatePanel component are printed in bold. <?php // Set the header header("content-type: text/html; charset=utf-8"); // Use bin or src? $strsources = '../bin'; // Import PRAjax require_once($strsources. '/PRAjax.php'); // Instantiate PRAjax $objprajax = new PRAjax($strSources. '/'); // Handle PRAjax client request $objprajax->handleclientrequest();?> <html> <head> <title>updatepanel</title> <?php $objprajax->getjavascript();?> <script language="javascript" src="../src/prajax_component_updatepanel.js"></script> </head> <body> <div style="width: 100%; height: 65px; background-color: #EEEEEE; font-family: Arial, Helvetica, Sans-Serif; font-size: 9pt;"> This example shows a partial page refresh using the UpdatePanel component. Try filling in your name. When you submit the form, PRAjax hooks the submit event and submits the form in the background. The whole page is then fetched and updated on-the-fly. <br> <a href="example_component_updatepanel.php.txt" target="_blank">view code...</a> Page 10 of 12

</div> <div id="divtest1" prajax_updatepanel="true"> <form name="frmtest1" style="font-family: Arial, Helvetica, sans-serif; fontsize: 11px;" prajax_updatepanelform="true"> Your name: <input type="text" name="txtname" id="txtname" style="width: 150px;"> <input type="submit" value="submit"> </form> </div> <div id="divtest2" prajax_updatepanel="true" style="font-family: Arial, Helvetica, sans-serif; font-size: 11px;"> <?=(isset($_post['txtname'])? 'You entered: '. $_POST['txtName'] : 'The submitted name will appear here...')?> </div> <div id="divtest3" style="font-family: Arial, Helvetica, sans-serif; fontsize: 11px;"> <?=(isset($_post['txtname'])? 'You entered: '. $_POST['txtName'] : 'The submitted name will not appear here, because this is not an UpdatePanel...')?> </div> </body> </html> Page 11 of 12

About The PRAjax library is written and maintained by Maarten Balliauw. Originally, it had its own encoding and decoding mechanism for passing data between client and server. This quickly evolved to JSON, which provides a smaller size for transferring data. PRAjax has been used by myself on different sites, and provides a convenient, semi-transparent layer between the client and the server. PRAjax contains 2 external libraries: Services_JSON, a PEAR library providing JSON conversions Authors: Michal Migurski <mike-json@teczno.com> Matt Knapp <mdknapp@gmail.com> Brett Stimmerman <brettstimmerman@gmail.com> http://pear.php.net/pepr/pepr-proposal-show.php?id=198 SAXParser, a class providing HTML parser functionality Author: Alexey G. Piyanin <drdrzlo@mail.ru> Visit the PRAjax website at. Page 12 of 12