SitePoint Sponsor

User Tag List

Results 1 to 15 of 15
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2002
    Location
    Wales
    Posts
    175
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Best ajax library to use with PHP?

    Hi All,

    I apologise if this is in the incorrect forum.

    I'm looking for an Ajax library which I can use with PHP to allow me to query the DB and return results, or update the DB without reloading the page. Most of the Ajaxy things I've seen update the page (div's etc.) and not the DB.

    I've looked over many Ajax libraries and admit to getting brain fog! So can anyone point me in the right direction for something like this.

    Thanks

    Rob

  2. #2
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    358
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ajax library cannot update DB, e.g. you cannot just send SQL to the database with Ajax library - it is not secure and safe to your database.

    You need to create JSON services with PHP, for example, and then query this services with any Ajax library. For example, I prefer the jQuery library.
    I'm creating trouble-free Apache, PHP, MySQL installer, WITSuite,
    and use it to setup my development environment.
    Demo, support, contact. Questions?

  3. #3
    SitePoint Zealot loathsome's Avatar
    Join Date
    Jul 2008
    Location
    Norway
    Posts
    121
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I second the jQuery recommendation. Very flexible, fast and have a relative easy learning curve.
    Time you enjoy wasting is not wasted time.

    Loathsome Systems

  4. #4
    Django Jedi neron-fx's Avatar
    Join Date
    Sep 2007
    Location
    Bristol/Bath, UK
    Posts
    274
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I third jQuery... blooming good Library.

    I have recently used it in an AJAX application for work which needed to update DB and retrieve from DB actively in real time without page refresh.
    Neron-Fx
    Everytime a user opens Internet Explorer, a web developer dies...
    http://www.savethedevelopers.org/

  5. #5
    SitePoint Zealot
    Join Date
    Jul 2002
    Location
    Wales
    Posts
    175
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for all your replies. I'll look into jQuery and if I have any more questions I'll post back here.

    Thanks again

    Rob

  6. #6
    SitePoint Zealot
    Join Date
    Jul 2002
    Location
    Wales
    Posts
    175
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi All,

    Well I've spent the last couple of days looking at masses of Jquery, Ajax, php resources from which I've learnt lots of great stuff and I'm enjoying the experience of learning something new, but now have a question:

    I'm having trouble working out how these things work together, for example. Say I want to create a Jquery image scroller; I've seen some of these which use JQ to modify a list of images (<li>image1 name </li> etc.) and use .slide etc. to animate them. All that I kind of understand but it's getting the images into the <li>'s in the first place. I'd use PHP to retrieve the image names from a MySQL DB and to add them to the html <li> items. Then Jquery can do its thing with the sliding. Would that work?

    Or do I need to do everything from the JQ i.e.

    ajax call to db to retrieve image names
    JQ to add to html LI's i.e. .append to LI's
    JQ to animate on mouse over etc.

    I *think* that's the way to go, but unclear.

    You can see my mind's a bit fuzzy. Can anyone help clear it up a bit?

    Rob

  7. #7
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    358
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There is no preferred way, I think. Both described methods will work but depending on other requirements you may prefer to use one or another.

    The only important point is that different approaches should not turn the code of your application into mess. If you prefer one of them, be straightforward, use one approach to resolve similar tasks.

    Personally, I prefer to store all presentation information in HTML template, I think that server should not return output with HTML tags. But in several projects I've used a opposite technique: server returns as much HTML as possible and JS only replace some parts of page with returned HTML.
    I'm creating trouble-free Apache, PHP, MySQL installer, WITSuite,
    and use it to setup my development environment.
    Demo, support, contact. Questions?

  8. #8
    SitePoint Zealot
    Join Date
    Jul 2002
    Location
    Wales
    Posts
    175
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Alex for getting back to me. I see what you're saying but in what order does the page get processed i.e. php parsed first then the JQ when the DOM is ready? It seems like the second method you've outlined would be the best for my purposes but wanted to make sure that I've got it straight in my mind.

  9. #9
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    358
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes. PHP parses page on the server and execute it and then send to client.
    On the client side JQ strikes when DOM is ready.

    The first approach requires two PHP scripts (or one static page and one PHP script):
    static page contains only some HTML with JQ and is not processed by PHP, PHP script returns only small part of information, required for building the widget. Of course this requires one more HTTP request to get the data. So, if you have several widgets, you have several HTTP requests to server (of course, this number can be decreased to just one, but it is another story.)
    I'm creating trouble-free Apache, PHP, MySQL installer, WITSuite,
    and use it to setup my development environment.
    Demo, support, contact. Questions?

  10. #10
    SitePoint Zealot
    Join Date
    Jul 2002
    Location
    Wales
    Posts
    175
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I *think* I'm getting it... If I wanted JQ/Ajax/JSON DB functionality I could still do it this way right?

    Tell me, can you point me in the direction of some examples by any chance?

  11. #11
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    358
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Right.

    Try jQuery ajax: http://docs.jquery.com/Ajax
    I'm creating trouble-free Apache, PHP, MySQL installer, WITSuite,
    and use it to setup my development environment.
    Demo, support, contact. Questions?

  12. #12
    We're from teh basements.
    Join Date
    Apr 2007
    Posts
    1,205
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    All JavaScript libraries rely on the same XMLHttpRequest or ActiveX browser objects, so there is no "best" one for the job. It's purely a matter of personal preference.

  13. #13
    We're from teh basements.
    Join Date
    Apr 2007
    Posts
    1,205
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Rob_H View Post
    Tell me, can you point me in the direction of some examples by any chance?
    Here's an instant messaging application I use on my BBS. It consists of a PHP servlet and a JavaScript client. The function ajax() is just a typical function that returns an XMLHttpRequest object based on the user's browser.

    This is for illustrative purposes only. I'm not going to bother posting the code for the PHP classes and includes or miscellaneous JavaScript functions and objects involved. Suffice it to say that most of the CoolMail class methods perform an SQL query and return the resultset as an array. The method CoolMail::encodeResponse() calls the built-in PHP function json_encode() to create the JSON string that will be sent in response to an AJAX request.

    /your_site/public_html/ajax_servlet/coolmail
    PHP Code:
    <?php

      
    require_once('../config.php');
      require_once(
    './fast_init.php');

      
    $cm = new CoolMail($Database);

      switch(
    $pathVars[0]) {
       case 
    "get_messages";
        
    $cm->getMessages($pathVars[1]);
        break;
       case 
    "save_message";
        
    $cm->saveMessage(urldecode($pathVars[1]),urldecode($pathVars[2]));
        break;
       case 
    "delete_message";
        
    $cm->deleteMessage($pathVars[1]);
        break;
       default:
        break;
      }

      
    header('Content-type: application/json');
      echo 
    $cm->encodeResponse();

    ?>
    Note that I use two XMLHttpRequest objects here. One is used to check the server for new messages every few seconds. The other is used to send messages.

    /your_site/public_html/client/coolmail.js
    Code:
    CoolMail = {
    
     version:               1.2,
     startTime:             null,
     pollInterval:          0,
     lastReceived:          null,
     inboxPopup:            null,
     editorPopup:           null,
     messages:              null,
     currMsg:               0,
     pollerXhr:             null,
     pollTimer:             null,
     senderXhr:             null,
    
     init:                  function(intvl) {
                             with (CoolMail) {
                              var dat = new Date();
                              startTime = dat.getTime();
                              pollInterval = intvl;
                              inboxPopup = PopupManager.create('coolmailInbox',400,400);
                              inboxPopup.setTitle('Instant Messages :: CoolMail v' + version);
                              inboxPopup.addButton('Reply','CoolMail.reply();');
                              inboxPopup.addButton('ReadNext','CoolMail.nextMessage();');
                              inboxPopup.showCloseButton = false;
                              editorPopup = PopupManager.create('coolmailEditor',400,405);
                              var edHtm = "<center><form id=\"coolmail_editor\"><table width=\99%\">"
                                        + "<tr><td align=\"left\">To:</td><td align=\"left\"><input type=\"text\" name=\"to\" value=\"\" size=\"55\" /></td></tr>"
                                        + "<tr><td colspan=\"2\" align=\"left\"><textarea cols=\"45\" rows=\"18\" name=\"body\"></textarea></td></tr>"
                                        + "</table></form></center>";
                              editorPopup.setContent(edHtm);
                              editorPopup.addButton('Send','CoolMail.send();');
                              editorPopup.addButton('Cancel','CoolMail.editorPopup.hide();');
                              editorPopup.showCloseButton = false;
                              pollerXhr = ajax();
                              lastReceived = 0;
                              messages = new Array();
                              pollTimer = window.setInterval('CoolMail.checkMessages()',pollInterval);
                              senderXhr = ajax();
                             }
                            },
    
     suspend:               function() {
                             with (CoolMail) {
                              clearInterval(pollTimer);
                              pollerXhr.abort();
                             }
                            },
    
     resume:                function() {
                             with (CoolMail) {
                              var dat = new Date();
                              startTime = dat.getTime();
                              pollTimer = window.setInterval('CoolMail.checkMessages()',pollInterval);
                             }
                            },
    
     checkMessages:         function() {
                             with (CoolMail) {
                              pollerXhr.abort();
                              var dat = new Date();
                              var now = dat.getTime();
                              if ((now - startTime) > 1800000) {
                               suspend();
                               if (confirm('You have been idle for awhile. Do you want to continue sending and receiving IMs?\n\nClick "OK" to continue using IMs. Click "Cancel" to disable IMs and this timeout message.')) resume();
                               else {
                                Preferences.setUserPref('enableIMs',false);
                                alert('Instant messaging disabled. To re-enable it, click "Preferences" at the top of the page.');
                                return;
                               }
                              }
                              var uri = "/ajax_servlet/coolmail/get_messages/" + lastReceived + "/" + randomString(32);
                              pollerXhr.open('GET',uri,true);
                              pollerXhr.onreadystatechange = CoolMail.loadMessages;
                              pollerXhr.send('');
                             }
                            },
    
     loadMessages:          function() {
                             with (CoolMail) {
                              if (pollerXhr.readyState == 4) {
                               if (pollerXhr.status == 200) {
                                var jsonObj = eval("(" + pollerXhr.responseText + ")");
                                if (!jsonObj.success) alert(jsonObj.error);
                                if (jsonObj.messages.length > 0) {
                                 for (var i=0;i < jsonObj.messages.length;i++) {
                                  messages.push(jsonObj.messages[i]);
                                  lastReceived = jsonObj.messages[i].id;
                                 } // for
                                 if (confirm('You have new private messages. Do you want to read them now?\n\nClick "OK" to read messages. Click "Cancel" to continue.')) showCurrMessage();
                                } // if
                               } // if
                              } // if
                             } // with
                            },
    
     showCurrMessage:       function() {
                             with (CoolMail) {
                              var msg = messages[currMsg];
                              var htm = "<center><table width=\99%\">"
                                      + "<tr><td align=\"left\">From:</td><td align=\"left\">" + msg.from + "</td></tr>"
                                      + "<tr><td align=\"left\">Date:</td><td align=\"left\">" + msg.timestamp + "</td></tr>"
                                      + "<tr><td  align=\"left\" colspan=\"2\">" + msg.body + "</td></tr>"
                                      + "</table></center>";
                              inboxPopup.setContent(htm);
                              inboxPopup.show();
                              deleteMessage(msg.id);
                             }
                            },
    
     nextMessage:           function() {
                             with (CoolMail) {
                              if (currMsg == (messages.length - 1)) {
                               messages = new Array();
                               currMsg = 0;
                               alert('No new messages.');
                               inboxPopup.hide();
                               return;
                              }
                              currMsg++;
                              showCurrMessage();
                             }
                            },
    
     compose:               function() {
                             with (CoolMail) {
                              editorPopup.setTitle('New Instant Message :: CoolMail v' + version);
                              if (arguments.length > 0) document.getElementById('coolmail_editor').to.value = arguments[0];
                              editorPopup.show();
                             }
                            },
    
     reply:                 function() {
                             with (CoolMail) {
                              editorPopup.setTitle('Reply to ' + messages[currMsg].from + ' :: CoolMail v' + version);
                              document.getElementById('coolmail_editor').to.value = messages[currMsg].from;
                              editorPopup.show();
                             }
    
                            },
    
     send:                  function() {
                             with (CoolMail) {
                              var recp = document.getElementById('coolmail_editor').to.value;
                              var body = document.getElementById('coolmail_editor').body.value;
                              var uri = "/ajax_servlet/coolmail/save_message/" + encodeURIComponent(recp) + "/" + Base64.encode(body) + "/" + randomString(32);
                              senderXhr.open('GET',uri,true);
                              senderXhr.onreadystatechange = CoolMail.confirmSent;
                              senderXhr.send('');
                              return false;
                             }
                            },
    
     confirmSent:           function() {
                             with (CoolMail) {
                              if (senderXhr.readyState == 4) {
                               if (senderXhr.status == 200) {
                                var jsonObj = eval("(" + senderXhr.responseText + ")");
                                if (!jsonObj.success) alert(jsonObj.error);
                                else {
                                 alert('Message sent.');
                                 editorPopup.hide();
                                 document.getElementById('coolmail_editor').reset();
                                }
                               }
                               else alert('HTTP error ' + senderXhr.status  + ' sending message.');
                              }
                             }
                            },
    
     deleteMessage:         function(msgId) {
                             with (CoolMail) {
                              var uri = "/ajax_servlet/coolmail/delete_message/" + msgId + "/" + randomString(32);
                              senderXhr.open('GET',uri,true);
                              senderXhr.onreadystatechange = CoolMail.confirmDeleted;
                              senderXhr.send('');
                             }
                            },
    
     confirmDeleted:        function(msgId) {
                             with (CoolMail) {
                              if (senderXhr.readyState == 4) {
                               if (senderXhr.status == 200) {
                                var jsonObj = eval("(" + senderXhr.responseText + ")");
                                if (!jsonObj.success) alert(jsonObj.error);
                               }
                               else alert('HTTP error ' + senderXhr.status + ' synchronizing with message server.');
                              }
                             }
                            }
    
    };

  14. #14
    SitePoint Zealot
    Join Date
    Jul 2002
    Location
    Wales
    Posts
    175
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow! Thank's to all of you for taking the time to post all this stuff and to you www for the code snippets. I'll need to digest this and look into JSON a bit more too as I've only just skimmed the surface. At this second it all looks daunting, but will sure keep me busy!

  15. #15
    We're from teh basements.
    Join Date
    Apr 2007
    Posts
    1,205
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    JSON is easy as pie. There are really only two major things to remember:

    1) Use json_encode() to turn a PHP object into a JSON string.

    2) Use this construct to turn the JSON string into a JavaScript object:

    Code:
    var obj = eval("(" + jsonString + ")");
    There may be flaws in this approach, but I've yet to see it not work.


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
  •