Delphi For PHP Forums       


Go Back   Delphi-PHP Forums > Programming > Javascript and Ajax
Forum Jump Register FAQ Members List Downloads Search Today's Posts Mark Forums Read

Javascript and Ajax Questions and information about working with Ajax and Javascript in Delphi for PHP.

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 12th February 2008, 05:17
405hp's Avatar
Firebug Fanatic
 
Join Date: Dec 2007
Location: State of Confusion
Posts: 3,076
405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute
Default Basic Ajax for d4php

**************
Updated 14th of November 2008
**************
I have streamlined everything as I have learned new things over the past year
the ajax_v2.zip attached files now use posts instead of gets and use a more elegant set of functions that you will find here: Favorite Functions to add to common.js

This approach now 'insulates' you from the routine. The bare minimum that you need to do an ajax process with this is now
Code:
var params='value1='+findObj('Edit1').value+'&value2='+findObj('Edit2').value
basicAjax("ajax_server1.php",params);
And then from the server you return only valid javascript - and nothing else.

You can also override the stock setting if you like by including your own function in the call
Code:
basicAjax("ajax_server.php","value1=Bob",myfunction);
or even something like
Code:
basicAjax("ajax_server.php","value1=Bob",function(){alert(xmlHttp.responseText)});
Again, the working samples are in ajax_v2.zip attached to the first post in this thread.

***************
**original thread**
***************
I finally learned how to easily send myself fast bits of information via ajax. The demo files are attached.

ajax_client.php (+xml) are the standard form type d4p program.
ajax_server.php is a unit that just serves up anything you want.

With this basic demo I'm just concatenating a first and last name but you can use it for almost anything.

Breaking down the buttons code:

This is just shorthand in case we will have multiple calls through out the program. I inserted this function into the pages before show event. It creates the browser specific ajax request:

var xmlHttp=createHTTPrequest();

This next one creates a function that fires when the server sends us back something we can work with. It can further check for proper html codes if you need to (200 400 404 500 errors etc) It could also just fire off an existing function on your form:

xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
/* Do something with the response */
findObj('Label1').innerHTML= '<b>'+xmlHttp.responseText+'</b>';
alert("Response from server: "+xmlHttp.responseText);
}
}


This line calls your script. You can talk to the server via the variables. ?v1=x&v2=y. The true means run it asynchronous, while a false would make it wait for a response no matter what. :

xmlHttp.open("GET","ajax_server.php?value1=Bob",tr ue);
xmlHttp.send(null);



This does not use any of the xajax script so you don't need to turn on use ajax.

First thing I'm going to use it for is to delete records from a table. I'll just send it the key I want to delete and run a plain sql statement to delete it. I'll return if it worked to a status label for example. Then I'll attack adding records to a table and inserting them in my existing dbgrid.

NOTE This was done in v1. In v2 they changed the default behavior of bitbutton to submit. Please change it to normal.
Attached Files
File Type: php ajax_server.php (311 Bytes, 214 views)
File Type: php ajax_client.php (2.6 KB, 181 views)
File Type: php ajax_client.xml.php (3.4 KB, 154 views)
File Type: zip ajax_v2b.zip (2.3 KB, 163 views)

Last edited by 405hp; 27th January 2009 at 20:17. Reason: updated ajax_v2b.zip
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 12th February 2008, 11:41
delphi-php's Avatar
Forum Admin
 
Join Date: Mar 2007
Location: London, UK
Posts: 595
delphi-php has a reputation beyond reputedelphi-php has a reputation beyond reputedelphi-php has a reputation beyond reputedelphi-php has a reputation beyond reputedelphi-php has a reputation beyond reputedelphi-php has a reputation beyond reputedelphi-php has a reputation beyond reputedelphi-php has a reputation beyond reputedelphi-php has a reputation beyond reputedelphi-php has a reputation beyond reputedelphi-php has a reputation beyond repute
Default

Thanks 405hp for the code samlpes!

Cheers ....
Gerald.
__________________
Don't forget to add to a users reputation if they have helped you.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 12th February 2008, 18:54
405hp's Avatar
Firebug Fanatic
 
Join Date: Dec 2007
Location: State of Confusion
Posts: 3,076
405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute
Default

Quote:
First thing I'm going to use it for is to delete records from a table.
Well that was easy. AND FAST!!!

I have a speed button (trashcan pic) and put this in jsclick ( ddOG is my dbgrid.)
Code:
                 var row = ddOG.getFocusedRow();
                if (!confirm('DELETE '+ddOG.getTableModel().getValue(4,row)+' from your order guide? ')) return (false);
                var xmlHttp=createHTTPrequest();
                xmlHttp.onreadystatechange=function()
                       {
                       if(xmlHttp.readyState==4)
                         {
                         ddOG.getTableModel().removeRows(row, 1);
                          }
                       }
                  xmlHttp.open("GET","ajax_deleteprod.php?cus="+document.getElementById('HiddenField1').value+"&prod="+ddOG.getTableModel().getValue(0,row),true);
                  xmlHttp.send(null);
                  return(false);
ajax_deleteprod.php - mini script
PHP Code:
//delete from both order files
        
include("global.inc.php");
        
pt_register('GET','cus','prod');
        require(
'connectdb.php');
               
$sql="DELETE FROM `Cust".$cus."` WHERE `Code`=".$prod;
               
$result=mysql_query($sql);//reorderguide
               
if (!$resultsqlErrors($sql);
               
$sql="DELETE FROM `cphist` WHERE `cust`=".$cus." and `prod`=".$prd;
               
$result=mysql_query($sql);//cphist
               
if (!$resultsqlErrors($sql);
  echo 
$prod.' deleted'
This replaced code variants

v1-Plain xajax call 6 seconds as it returned the dbgrid full of stuff.
v2- xajax call that updated nothing 2 seconds because it loads the whole form.

This one - Less than 1 second most of the time... And it happens transparently. example I can press confirm and if I'm fast enough, click away on my dbgrid and when it returns the product just disappears.

For full disclosure here are the include files.

PHP Code:
function pt_register()
{
  
$num_args func_num_args();
   
$vars = array();

   if (
$num_args >= 2) {
       
$method strtoupper(func_get_arg(0));

       if ((
$method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die(
'The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       
$varname "HTTP_{$method}_VARS";
      global ${
$varname};

       for (
$i 1$i $num_args$i++) {
           
$parameter func_get_arg($i);

           if (isset(${
$varname}[$parameter])) {
               global $
$parameter;
               $
$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die(
'You must specify at least two arguments');
   }


PHP Code:
function sqlErrors($query)
               {
                       
//debug log
               
$message  ' - <b>Invalid query:</b><br>' mysql_error() . '<br><br>';
               
$message .= '<b>Whole query:</b><br>' $query '<br><br>';
               
$file="sqlerror.html";
               
$handle fopen($file"a");
               
$regdate=date('Y/m/d H:i:s');
               
fwrite($handle$regdate);
               
fwrite($handle$message);
               
fclose($handle);
               }

$hostname='localhost';
$username '***';
$password '***';
$dbname "***";
$server mysql_connect($hostname,$username$password) or die("Connection to database failed!");
// Select the database now:
$connection mysql_select_db($dbname$server); 
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 13th February 2008, 10:14
D4PHP Guru
 
Join Date: Nov 2007
Posts: 218
u.masotti is on a distinguished road
Thumbs up

Good!
This is a variant to select which methods filter: add or remove from $methods array what you don't care.
BTW: $vars array isn't used.

[quote=405hp;5226]
PHP Code:
function pt_register()
{
  
$num_args func_num_args();
  if (
$num_args >= 2)
       
$method strtoupper(func_get_arg(0));
  else
       exit(
'You must specify at least two arguments');
  
$methods=array("SESSION","GET","POST","SERVER","COOKIE","ENV");
  if ( !
in_array $method$methods )){
     
$s0 'First argument of pt_register() must be in ( ';
     foreach ( 
$methods as $s1 )
       
$s0.=$s1.' ';
     exit(
$s0.')');
   }
   
$varname "HTTP_{$method}_VARS";
   global ${
$varname};
   for (
$i 1$i $num_args$i++)
   {
       
$parameter func_get_arg($i);
       if (isset(${
$varname}[$parameter])) 
       {
          global $
$parameter;
          $
$parameter = ${$varname}[$parameter];
       }
   }

__________________
Ciao.
Mimmo.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 13th February 2008, 10:45
D4PHP Guru
 
Join Date: Nov 2007
Posts: 218
u.masotti is on a distinguished road
Default

As you can see, there is a part of code that is a constant, and some code depending on what you're doing. This is your code commented:
Code:
 // variable beforeAjax code: prepare variables and/or confirmation requests
 var row = ddOG.getFocusedRow();
 if (!confirm('DELETE '+ddOG.getTableModel().getValue(4,row)+' from your order guide? ')) return (false);
 // end ******
 // constant before
 var xmlHttp=createHTTPrequest();
 xmlHttp.onreadystatechange=function()
 {
    if(xmlHttp.readyState==4)
    {
      // variable AfterAjaxCompletion
      ddOG.getTableModel().removeRows(row, 1);
      // end *********
    }
}
// variable OnAjaxCall server procedure
xmlHttp.open("GET","ajax_deleteprod.php?cus="+document.getElementById('HiddenField1').value+"&prod="+ddOG.getTableModel().getValue(0,row),true);
                  xmlHttp.send(null);
                  return(false);
// end ********
To test component development (i'm reading guide), I'd make a simple component, SimpleAjax, to connect these three variable events.
Only problems, from my POV, is to pass variables from beforeAjax() to afterAjaxCompletion(). Maybe I must use a params Array() parameter.
__________________
Ciao.
Mimmo.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 13th February 2008, 14:29
405hp's Avatar
Firebug Fanatic
 
Join Date: Dec 2007
Location: State of Confusion
Posts: 3,076
405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute
Default

pt_register() is a function I found in something many years ago. I just thought it was a nice idea and started using it out of habit.

I'm not sure about the after completion var as I could see using it for 20 or more lines of code.

What I would guess at is you just use it as a way of passing control to another function, or as part of the component include a jswrapper that is called simpleAjax onCompletion or something.

Another option would be to just have this component fill in the js event with place holders for your code - example the way the ide does when you click on bitbutton and then click js onclick event and it prepares the //put your code here.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 13th February 2008, 15:57
D4PHP User
 
Join Date: Jan 2008
Posts: 31
omar is on a distinguished road
Default

hi thanx for that ....
i use this php code that u can use to built ur xml file from query result

$dbresult = mysql_query($query, $dbconnect);
$num=mysql_num_rows($dbresult);

if ($num==0)
{
$xml='<?xml version="1.0" encoding="Windows-1256" standalone="yes"?><root><prisoners></prisoners></root>';
}
else
{
$xml='<?xml version="1.0" encoding="Windows-1256" standalone="yes"?><root>';
while($row = mysql_fetch_assoc($dbresult))
{
$xml=$xml."<result>";
foreach ($row as $fieldname => $fieldvalue)
{
$xml=$xml."<".$fieldname.">".$fieldvalue."</".$fieldname.">";
}
$xml=$xml."</result>";
}
$xml=$xml."</root>";
}
header('Content-Type: text/xml');
echo $xml;
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 13th February 2008, 17:58
405hp's Avatar
Firebug Fanatic
 
Join Date: Dec 2007
Location: State of Confusion
Posts: 3,076
405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute
Default

Thanks omar,

For now I think I will skip using xml as anything I do with this will be from me on both ends so I can control what is returned to the client. Just seems to me to be a bother encoding and then decoding when I know what to expect.

For sending multiple things I just figured this out

Change the server line to
PHP Code:
$ret.= "dog, tree, cat"
and in the client
Code:
var myarray=xmlHttp.responseText.split(/\s*,\s*/);
alert(myarray[1]);
I can then do multiple different things with the different elements in the array.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 13th February 2008, 18:34
D4PHP User
 
Join Date: Jan 2008
Posts: 31
omar is on a distinguished road
Default

look i built a complete project with php-mysql using ajax .. it was nice but it take long time ... i was using dreamweaver as editor ...

i built most of controls even the gird i draw it...

but now i prefer to use d4php .... but i notice that ajaxcall is slow with it....
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 13th February 2008, 18:42
405hp's Avatar
Firebug Fanatic
 
Join Date: Dec 2007
Location: State of Confusion
Posts: 3,076
405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute405hp has a reputation beyond repute
Default

Quote:
Originally Posted by omar View Post

but i notice that ajaxcall is slow with it....
Yes, I think it's one of the major problems. Which is why I had to figure this out.

This turned out easy enough that I'm not that concerned any more though.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT +1. The time now is 21:04.




Powered by vBulletin® Version 3.7.3
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0 ©2009, Crawlability, Inc.
Copyright © 2004 - 2009, G&J Solutions Ltd. All Rights Reserved. terms of use