DiigIT | IT Community
No Profile Image
Welcome Guest
New User? Register | Login

how to do ajax and modal popups and displaying loading

By: Shailesh Singh | 15 Sep 2008 9:40 am

Hi All,
  I am doing One Consultancy project.I am new to PHP with AJAX.In php how to do ajax and modal popups and displaying loading and so on.If any body have sample examples php with ajax please send it me.
 
thank you in adavance

Comments

// Calling Javascript Function

<input name="word" id="word" tabindex="1" type="text"
class="top_search_ input" onKeyUp='JavaScript :xmlhttpPost
("searchfunc. php","result" )'>
<!-- inner search start here -->
<div id="result"> &nbsp;</div>
<!--inner search start here-->

// Calling Javascript Function

create a php file(searchfunc. php), that simply displays the data
results (either query results) / divs / tables / anything you wish to
return in result

//// Javascript file :

// JavaScript Document
function xmlhttpPost( strURL,dv) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequ est) {
self.xmlHttpReq = new XMLHttpRequest( );
}
// IE
else if (window.ActiveXObje ct) {
self.xmlHttpReq = new ActiveXObject( "Microsoft. XMLHTTP") ;
}
self.xmlHttpReq. open('POST' , strURL, true);
self.xmlHttpReq. setRequestHeader ('Content- Type', 'application/ x-
www-form-urlencoded ');
self.xmlHttpReq. onreadystatechan ge = function() {
if (self.xmlHttpReq. readyState == 4) {
updatepage(self. xmlHttpReq. responseText, dv);
}
if (self.xmlHttpReq. readyState == 1) {
document.getElement ById(dv). innerHTML = '<img
src="images/ search_images/ ajax-loading. gif" />';
}
}
self.xmlHttpReq. send(getquerystr ing());
}

function getquerystring( ) {
var word = document.getElement ById('word' ).value;
var loc = document.getElement ById('loc' ).value;
if(word!=null) {
qstr = 'w=' + escape(word) ; // NOTE: no '?' before
querystring
if(loc!=null)
qstr = qstr + '&l=' + escape(loc); // NOTE:
no '?' before querystring
}
return qstr;
}

function updatepage(str, dvs){
document.getElement ById(dvs) .innerHTML = str;
}

/// Javascript File
By: Shailesh Singh | 15 Sep 2008
try to visit this site http://www.w3school s.com/ajax/ default.asp.
there's a lot of sample about ajax, how to use in php.. that would
help you..
By: Shailesh Singh | 15 Sep 2008
Hi, I would suggest you to go for jQuery (www.jquery. com). jQuery UI has all the components you need.
By: Shailesh Singh | 15 Sep 2008
Have a look at prototype.js at http://www.prototyp ejs.org/ which has
excellent support for Ajax.

Here's an example. The code below comes from two files. The first is
the HTML and the second is a php file (which could be converted to a
class). All you need to do is download the prototype javascript
library and put it in your directory system, thus:
/prototype/js/ prototype. js. Read the prototype documentation and all
will be clear, hopefully.

Have a look at JSON - you could start here:
http://en.wikipedia .org/wiki/ JSON

============ ========= ==
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional/ /EN">
<HTML>
<HEAD>
<title>AjaxExample< /title>
<META HTTP-EQUIV=" CACHE-CONTROL" CONTENT="NO- CACHE">
<META HTTP-EQUIV=" PRAGMA" CONTENT="NO- CACHE">
<META HTTP-EQUIV=" EXPIRES" CONTENT="-1" >
<script src="/prototype/ js/prototype. js"
type="text/javascri pt"></script>
<style>

a { color:#442b62; text-decoration: underline; }
a:link { color:#442b62; text-decoration: underline; }
a:visited { color:#442b62; text-decoration: underline; }
a:hover { color:#8e57d0; }
a:active { color:#8e57d0; }

body{
text-align:left;
font-size:100. 01%;
font-family: Arial, helvetica, sans-serif;
color:#a4a4a4;
background-color: #fff;
margin:20px;
padding:0;
}
h1 {
font-weight: bold;
font-size:24px;
}
img{
border:none;
}
.title {
font-weight: bold;
font-size:16px;
}
.text {
font-weight: bold;
font-size:12px;
}
.link {
font-weight: bold;
font-size:12px;
}
#content {
color:#c40000;
}
#monitor {
color:#0000c4;
}
</style>
</HEAD>
<body>
<form name="userForm" id="userForm" method="get" >
<table border="0" cellpadding= "4" cellspacing= "0">
<tr>
<td width="100%" colspan="2"> <h1>Simple AJAX Name Search
Example</h1>
</td>
</tr>
<tr>
<td class="title" width="100%" colspan="2"> See ajaxManager. php for
details regarding the server side code.</td>
</tr>
<tr>
<td width="100"> Name search pattern:</td>
<td><input type="text" id="pattern" name="pattern"
onkeyup="show_ data();"> </td>
</tr>
<tr>
<td width="100" valign="top" >Results: </td>
<td>
<div id="resultMessage" name="resultMessage "></div>
</td>
</tr>
<tr>
<td width="100" valign="top" >Matching names:</td>
<td>
<select name="personList" id="personList"
style="width: 200px;size: 0;"><option value="None" >None</option> </select>
</td>
</tr>
</table>
</form>
<br /><br />
<div class="link" ><a
href="/prototype/ index.html" >&lt;&lt; Back</a>< /div>

<script type="text/javascri pt">
<!--//
// This is an example of using Ajax.

function show_data() {

// Initialise results fields.
$('resultMessage' ).innerHTML = '';
clearPersons( 'Searching. ..');

if ($('pattern' ).value.length <= 0) {
clearPersons( 'None');
}
else {
//Append the name to search for to the requestURL
// To ensure IE7 does not ignore the no-cache directive, insert a
unique value in the url.
var now = new Date();
var url = 'ajaxManager. php?t='+now. getTime() +'&';
// Note use of the prototype '$' function to get the element by id.
var params = ('action=GetUserNam esExample' +
'&pattern=' + $('pattern') .value);

// Create an Ajax Request object to handle the request.
var ajax = new Ajax.Request(
url,
{ method: 'get',
parameters: params,
onSuccess: reportSuccess,
onFailure: reportError,
asynchronous: false
});
}
}

function reportError( request) {
alert("An error was detected during processing. Please contact the
website administrator. \n" +
"Error text: "+request.responseT ext);
}

function reportSuccess( request) {

//alert("reportSucc ess called with: "+request.responseT ext);

// Use the JSON object returned from the server to populate the
result.
var obj = eval(request. responseText) ;
if (obj.status= ='ok') {
$('resultMessage' ).innerHTML = obj.message;
// Do something with the returned data.
loadPersons( request);
}
else {
$('resultMessage' ).innerHTML = obj.message;
alert("An error was detected during processing:\ n"+obj.message) ;
clearPersons( 'None');
}

}

function loadPersons( request) {
// Use the JSON object returned from the server to populate the
result.
var obj = eval(request. responseText) ;
if (obj.status= ='ok') {
if (obj.dataArray. length>0) {
for (var i=0; i<obj.dataArray. length; i++) {
var item = eval(obj.dataArray[ i]);
//alert('id= '+item.id+ ', name='+item. name);
// Load the listbox with the result.
document.userForm. personList[ i]=new Option(item. name, item.id);
}
}
else {
alert('No entries were found for the selection criteria.');
}
}
else {
alert("An error was detected during processing:\ n"+
"Error text: "+obj.message) ;
}
}

function clearPersons( optionText) {
var len = document.userForm. personList. length;
for (var i=0; i<len; i++) {
// NB Just keep removing the first element, because the list changes
dynamically
// when removing entries.
document.userForm. personList. remove(0) ;
}
document.userForm. personList[ 0]=new Option(optionText, 'null');
}

// -->
</script>
</body>
</HTML>

============ ========= ==
<?php

$personDataAry =
array('Abraham' ,'Arthur' ,'Mickey' ,'Charlie' ,'Freddie' ,'George' ,'Harry', '
Ian',

'Mary','Betty' ,'Valerie' ,'Zebedie' ,'Horace' ,'Orist', 'Nathan', 'Jayden',

'Dave','Ricky' ,'Nathaniel' ,'Patrick' ,'Peter', 'Barrie', 'Jimmy',' Bart',

'Gordon','Roger' ,'Steve', 'Louise', 'Kim','Ben' ,'Russ',' Maggie');
sort($personDataAry );

$jsonVar = "fiddle";
// Handle Ajax action request.
$action = $_REQUEST["action" ];
switch($action) {
case "GetUserNamesExampl e":
$jsonVar = handleGetUserNamesE xample($_ REQUEST[" pattern"] );
break;
// Put your customer request action processing here.
// ...
default:
// Unknown request action.
$jsonVar = ("result={ "
+" status:'error' "
+",message:' Unknown action "+$action+"' "
+"};");
break;
}
print($jsonVar) ;
exit();


/// <summary>
/// Example method for handling the GetUserNamesExample action.
/// </summary>
function handleGetUserNamesE xample($p_ pattern) {
global $personDataAry;

// Set up variables we will be returning to the caller, via a JSON
object.
$personAry = array();
$status = "ok";
// Do our various processing to determine the state of the returned
vars.
// This would normally be a db lookup. Hard coded here for
illustration only.
$atLeastOne = false;
for($i=0; $i<count($personDat aAry); $i++) {

$pos = stripos($personData Ary[$i], strToLower($ p_pattern) );
if ($pos===false) {
// Did not find any hits.
}
else if($pos>=0) {

$atLeastOne = true;

$person = new Person();
$person->id = "ID".$i;
$person->name = $personDataAry[ $i];
$personAry[] = $person;
}
}
if ($atLeastOne) {
$message = 'Returned '.count($personAry) .' elements';
} else {
$status = "error";
$message = "Try another search pattern";
}
// Build the JSON object we are going to return to the caller.
return convertArrayToJson( $status, $message, $personAry);
}

/// <summary>
/// Iterate through the array of return person and convert to a JSON
parameter.
/// </summary>
function convertArrayToJson( $p_status, $p_message, $p_array) {

// Build the JSON object we are going to return to the caller.
// Also include the status of the processing, the returned data and
any messages.
$jsonVar = ("result={ "
." 'status':'". $p_status. "'"
.",'message' :'".$p_message. "'"
.",'dataArray' :[");

if (isset($p_array) && is_array($p_ array) && count($p_array) >0) {
$comma = "";
foreach($p_array as $obj) {
if(!empty($obj) ) {
// Add JSON array element for each object.
$jsonVar .= ($comma.$obj- >getAsJsonObject ());
$comma = ",";
}
}
}
$jsonVar .= ("]"."};");
// Return the result.
return $jsonVar;
}

class Person
{
var $id;
var $name;

function getAsJsonObject( ) {
return("{'id' :'".$this- >id."'"." ,'name':' ".$this-> name."'". "}");
}
}

?>

============ ========= ==

That should help.
By: Shailesh Singh | 15 Sep 2008
try xajax. its best, *xajax*project. org
By: Manoj | 15 Sep 2008
how about using jquery.com or prototype or any other frame work. its easy to use .
even i saw a nice simple example on ajax in w3schools. what you really need to do in ajax what is your requirement
By: Manoj | 19 Sep 2008
http://www.pgdesign ing.com/ajax/ 2008/04/16/ 37-more-shocking -jquery-plugins/
By: Manoj | 19 Sep 2008
http://nodstrum. com/2007/ 09/19/autocomple ter/

this is a complete php sample with jquery AJAX
By: Manoj | 19 Sep 2008

Leave a comment

Enter the text in the image
img
Can't read?
Type the characters you see in the picture below.


Close Move