Using Ajax to retrieve data

Discussion in 'Web Design and Development' started by Cabbit, Apr 18, 2009.

  1. Cabbit macrumors 68020

    Cabbit

    Joined:
    Jan 30, 2006
    Location:
    Scotland
    #1
    I would like to know a tutorial or some sample code i can look though that uses Ajax to preform the function of displaying records from a sql database on the fly without user intervention.

    Say i have 2 records in my database and i have called them onto my page, then another record is added to the database from another user. I want something capable of changing the records i am viewing to now include the new record.

    My last attempt at this i just called in the .php file to refresh every 5 seconds but that is not what i want to do and i would like to be able to get ajax working better for the newer projects i am working on.
     
  2. Me1000 macrumors 68000

    Me1000

    Joined:
    Jul 15, 2006
    #2
    Are you using any javascript libraries which may aid in this?

    js libraries usually aid tremendously in AJAX calls, because some *COUGH* browsers are quirky with AJAX.
     
  3. Cabbit thread starter macrumors 68020

    Cabbit

    Joined:
    Jan 30, 2006
    Location:
    Scotland
    #3
    well i am researching jquery but i am hoping to accomplish this in a more raw manner.
     
  4. bootedbear macrumors 6502

    bootedbear

    Joined:
    Sep 13, 2004
    Location:
    Austin, TX
    #4
    I do exactly this sort of thing frequently employing jQuery. I can't imagine ever going back to writing quirky Ajax code by hand -- there's really nothing to be gained by it.

    A frequent pattern I use is to make a request using the $().load() method to a server-side resource that returns a formatted table of the query results. For example:

    $('div#resultsGoHere').load('/someUrl');

    Where the div with id resultsGoHere is to be loaded with the table.

    Easy as pie!
     
  5. Cabbit thread starter macrumors 68020

    Cabbit

    Joined:
    Jan 30, 2006
    Location:
    Scotland
    #5
    easy as pie to you but i don't think i am getting it to work as expected.

    index.php
    PHP:
    <html>
    <
    head>

    <
    script src="jquery.js" language="javascript" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $("#table").load("db.php");
            $(document).ready(function() { 
               alert('hi'); 
            }); 
    </script>


    </head>
    <body>
        <h1>Results</h1>
        <div id="table"></div>
    </body>
    </html>

    db.php
    PHP:
    <?php

    $link 
    mysql_connect('localhost''root''root');
    if (!
    $link) {
        die(
    'Could not connect: ' mysql_error());
    }

    $sql "SELECT `username` FROM test.`tbl_activeusers`";
    $result mysql_query($sql) or die("Query failed($sql): " mysql_error());

    while(
    $row mysql_fetch_array($result)) 
    {
        echo 
    $row['username'];
        echo 
    '<br />';
    }

    mysql_close($link);

    ?>
     
  6. Cabbit thread starter macrumors 68020

    Cabbit

    Joined:
    Jan 30, 2006
    Location:
    Scotland
    #6
    ok i got it displaying the data but it does not update the data without a refresh

    PHP:
    <html>
    <
    head>

    <
    script src="jquery.js" language="javascript" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(function(){
            $("#table").load("db.php");
          });
        $(document).ready(function() { 
               alert('hi'); 
        }); 
    </script>

    </head>
    <body>
        <h1>Results</h1>
        <div id="table"></div>
    </body>
    </html>
     
  7. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #7
    You'll need to use the setTimeout or setInterval functions to call that code after a certain amount of time. The trickier part here is figuring out how to tell if new data has been added or just update the table no matter if new data was added or not. You could keep a local variable that maybe keeps the number of records in the DB and check against that, or if the records have a timestamp you can check against that. Just some ideas.
    HTML:
    <script language="javascript" type="text/javascript">
        $(document).ready(function(){
            $("#table").load("db.php");
            // Do data load every 5 seconds
            setInterval( function() { $("#table").load("db.php"); }, 5000 );
          });
        $(document).ready(function() { 
               alert('hi'); 
        });
    </script> 
     
  8. Cabbit thread starter macrumors 68020

    Cabbit

    Joined:
    Jan 30, 2006
    Location:
    Scotland
    #8
    In safari activity it shows a new db.php file every 5 seconds is this normal or is there a way to reduce the load.
     
  9. Cabbit thread starter macrumors 68020

    Cabbit

    Joined:
    Jan 30, 2006
    Location:
    Scotland
    #9
    One wee thing i am noticing more often is javascripts no longer being in the header tag instead moving down below the page.
    Something mentioned is that it reduces the time it takes for a page to load, does this have merit?
     
  10. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #10
    Well, the interval was setup for 5 seconds, so yes it will access that file that often. The JavaScript can't simply know the DB has changed. This has to been done as a pull operation rather than a push from the server. This is the same way as all those other sites do this. You can increase the time interval, it would be the easiest thing to do. You could try tying the call the an event rather than simply time. You can get creative here.

    As for moving JavaScript to the end of the page; It depends on what your JavaScript is doing, but overall a page takes the same amount of time to load no matter the order because a file size will still take the same amount of time to download. The difference lies in what the user perceives. If your JavaScript needs to do a bit of AJAX and waiting for calls, then it can be help to have it run after the rest of the page items as the page elements will be downloaded and shown on the page before the JavaScript runs.

    This can also backfire, if the JavaScript is going to be adding elements to the page, then the user will see the page morphing and jumping around as new stuff is added, which for me looks tacky. For myself, I put all JavaScript in the head and anything that needs access to the DOM is executed after the page load using the onload (or similar) event.
     
  11. bootedbear macrumors 6502

    bootedbear

    Joined:
    Sep 13, 2004
    Location:
    Austin, TX
    #11
    The whole purpose of the jQuery "ready handler" is to allow you to run setup code at the optimum time.

    It fires after the DOM had been loaded (so that you can manipulate it) but before waiting for images to load (as onload does) and before the page has a chance to start being "drawn". This avoids the undesirable "jumping around" that angelwatt so rightly warned against.
     

Share This Page