AJAX - update table and selects

JavaScript and client side scripting.

Moderator: General Moderators

User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

AJAX - update table and selects

Post by Stryks »

I'm putting together a table, which I'd like to have update dynamically as you use some controls to flip though multiple pages of data. I'm also going to be using a search button to filter the data in the table.

The problem I have is that I'm calling HTML inserts for the table, and I'm not sure how to pull the extra information for the pagination control. I've been looking as using JSON to pull a total record count along with the page of data, but it's hard going getting it to work, particularly as I need the rows to allow for a double click to open a drill-down view. Building the table dynamically with js with that kind of control seems beyond me.

So, can anyone help me to create a table with pagination controls (like access) which update themselves and the table content with a single AJAX call?

Many thanks
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: AJAX - update table and selects

Post by pickle »

Why not just completely overwrite the table with your AJAX call, rather than dynamically build it.

JQuery has a lovely load() function to do exactly that: http://docs.jquery.com/Ajax/load#urldatacallback
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: AJAX - update table and selects

Post by Kieran Huggins »

mmmmmmm.... jQuery!
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Re: AJAX - update table and selects

Post by Stryks »

I'm actually using Prototype and Updater to pull HTML at the moment.

Why do you guys love jQuery so much. I took a quick peek and gave it up as a bad idea. I kinda suck at javascript, but I can usually read and comprehend it if I sit and focus for a while. Looking at jQuery code just left me baffled.

Should I take the time to learn it? What are the advantages over other packages, like prototype? Yeah ... why do you love it so much?

Oh .. back on topic, I was originally overwriting the entire table, but I wanted to update the pagination as well. For some odd reason it didn't occur to me to update the pagination controls as well. :roll:

Anyhow. I have done that now, but I'm still getting a situation where I seem to have to make multiple AJAX calls. My table has the data and the pagination controls, and initially, it returns all the data. But I also have some dropdown boxes to allow the user to filter the results.

There is more than one dropdown, so I had considered that instead of allowing a user to choose a dropdown combination that had no results, I would set up a chained select which would show only combos that had results. For example, lets say the first box option was 'department a'. You would select it, and the second dropdown would update to show the different types that have entries for that department, AND the table would update to show only the rows for the selected departments.

Maybe I just let them choose from all options in the dropdown and if it returns no results, well .. so be it.

Then there is the issue of working in the text filter, but ... thats another story.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: AJAX - update table and selects

Post by pickle »

If your PHP is up-to-date, you could get it to return a JSON object that you could then pull apart. So, rather than having the AJAX call just return straight code, you'd have a JSON object you could then reference like:

Code: Select all

/* pseudo-code-ish */var ret_val = resultFromAJAXCall() document.table = ret_val.tableCode;document.pagination = ret_val.pagination;document.pulldown1 = ret_val.pulldown1;//etc 
As for why I like jQuery: I have to admit I didn't at first. The syntax seemed really messed up. However, after playing around with it, I started to love it. If I had to sum it up in one word, I'd say "brevity". I've never used prototype, but jQuery let's me do amazingly compex things (that I previously invested days coding) with just 1 (albiet long) line of code.

Plus, ~Kieran's such a jQuery whore that I couldn't think of anything else when I was looking at Javascript libraries ;)
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Re: AJAX - update table and selects

Post by Stryks »

So ... generate the table and dropdowns as HTML, store in strings, and then pass them off as array elements to json_ecode()?

I might have to have a look at jQuery, as the prototype method I am using outputs the returned data directly to a specified area. As you say, I'll need to break it up to display it in separate parts of the screen.
pickle wrote:Plus, ~Kieran's such a jQuery whore that I couldn't think of anything else when I was looking at Javascript libraries ;)


:lol:
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: AJAX - update table and selects

Post by pickle »

Just a note though that the load() function I linked to earlier can't deal with JSON. You'll have to use the $.ajax method if going with jQuery.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Re: AJAX - update table and selects

Post by Stryks »

Ok, I've finally had some time to set some other things aside to take a good hard look at jquery.

And ... I'm already stumped. :banghead:

I want different things to happen at different times.
  • when a row is clicked, redirect to a new page with a different ID per row passed as GET
  • Table and comboboxes to update on combobox change
  • Table to update on page load
Starting with last things first ... I added the following to index.php

Code: Select all

<script type="text/javascript" src="<?php echo PATH_JS; ?>jquery.js"></script>
<script>
    $(document).ready(function(){
        $.getJSON("includes/ajax/tbl_main.php",
        function(json){
            alert("Data Loaded: " + json);
        });
    });
</script>
And in tbl_main.php, which used to just output straight HTML, I just wrapped it in ob_start() and ob_get_clean() calles and stored with ...

Code: Select all

   $json['table'] = ob_get_clean();
    echo json_encode($json);
This presents me with an alert saying
Data Loaded: [object Object]
Fair start. If I break open firebug I can see that the HTML data was sent back in JSON format. I'm assuming that I can now access json['table'], but I cant see how to assign it to a named div.

Actually, what I have in mind is that whatever data is needed will be returned as a JSON value, and will be assigned to divs based on the name it was stored with. So, if the AJAX call was made without parameters, then it would just return the JSON value 'dataview' which would be output to the object named dataview. If parameters were passed (by changing the dropdowns) then two values would be returned, 'dataview' and 'filters'.

Thats the idea anyhow. Can anyone tell me if I am barking up the wrong tree with this approach? And wither way, can one of you jQuery gurus help me out a bit? Code would be great, but a point in the right direction would be good too.

Many thanks.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: AJAX - update table and selects

Post by pickle »

Putting this line inside your function should populate the div

Code: Select all

$("#id-of-div-to-modify").html(json.table);
Of course, you should probably do some error checking to make sure 'table' exists.

As for your first problem, something like this could work:

Code: Select all

$(".class-of-row-clicked").click(function{    var id = $(this).attr('id');    window.location = 'http://www.yourdomain.com/redirect_page.php?id='+id;});
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: AJAX - update table and selects

Post by Kieran Huggins »

I'm confused, are you getting the resulting table data as JSON or HTML? Can you paste an example?
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: AJAX - update table and selects

Post by pickle »

I think he's getting the value passed back as JSON. One of the attributes in the JSON object is an HTML string.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Re: AJAX - update table and selects

Post by Stryks »

Yeah, basically, I'm generating HTML sections and passing them to json_encode(). The idea basically being to update whatever sections of the page are returned. So I might have ...

Code: Select all

$json['table'] = "<strong>table HTML</strong>";
$json['filter'] = "<strong>dropdown HTML</strong>";
 
echo json_encode($json);
 
... in an ajax call, and I'm wanting to get the json data, break it back into HTML sections, and assign them to their associated locations.

The code for the assignment of the returned element works like a charm. Would it be possible to do something like .... (excuse my poor excuse for psuedocode)
foreach(json as id=>data) if exists element with an ID of id then $(#id).html(data)
Or perhaps I should just check for the existence of each updatable section in json and assign them as I am above.
if exists json.table then $(#table_div).html(json.table)
if exists json.filter then $(#filter_div).html(json.filter)
With the second part, getting the click action for the rows, how do I assign an id to each row? Usually I'd embed the javascript in an onclick event and just be done with it, but it's messy as anything, and having a handler at the top like this might make it much more manageable in the long run.

EDIT - Oh ... I think I get it now ... it's checking the rows by class, and each row will have the id attribute set. Cool. But now I'm stuck for how to do both ... having them both together seems to break both of them.

As always ... many many thanks for the assistance. :)
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Re: AJAX - update table and selects

Post by Stryks »

Ok ... progress is slow, but thanks to your help there is at least some progress. :)

This is the current events script ...

Code: Select all

<script>
    $(document).ready(function(){
        $.getJSON("includes/ajax/tbl_main.php",
        function(json){
            
            // update the chartBox
            $("#dyn_tbl").html(json.dyn_tbl)
            
            // update the nav buttons
            //$(".navbutton").attr({'id': json.btn_last});
            
            // check for row clicks
            $(".tbl_row").click(function(){
                var id = $(this).attr('id');
                window.location = 'nmi_view.php?meter='+id;
            });
        });
    });
</script>
 
That works OK, and clicking on the rows of the table forwards as you might expect. You'll notice that I had to move the click event handler for the tbl_row into the document.ready function. I found that after the table was updated with ajax, the events no longer triggered. Restating the event after load fixes that.

I started to see a chicken and the egg issue though. If I have the pagination controls as a part of the table (tfoot) then it will be updated along with the rest of the ajax load. That would mean restating the event handler for the pagination controls, which would include the reloading of the table (including the pagination controls).

So I thought I'd separate them by loading the table data into the tbody, and using actual JSON data to update the pagination. So I started shooting back the following in my JSON.
{"btn_first":0,"btn_prev":0,"btn_next":2,"btn_last":6,"dyn_tbl":"<tr class=\"tbl_row\" id=\"825\"><td
><img src=\"\/includes\/images\/btn_tbl_mark.png\" border=\"0\" width=\"20\" height=\"20\" alt=\"selector
\"><\/td><td>6203399880<\/td><td>VAUGHAN ST<\/td><td>Type Not Set<\/td><td>Department Not Set<\/td><
\/tr>"}
Anyhow, so now I've added the following to the end of the script block above to try and catch button clicks ... but for some reason it's not firing.

Code: Select all

   // check for pagination clicks
    $(".navbutton").click(function(){
        //var id = $(this).attr('id');
        alert('Jumping to page #');
        //$.getJSON("includes/ajax/tbl_main.php", { page: id})  
    });
 
Clearly I'm backing it down to try and see where it's firing, but to no avail. The HTML for navbutton is the following by the way.

Code: Select all

               <tfoot>
                    <td colspan="4">
                        <a class="navbutton" id="2"><img src="/includes/images/btn_pag_first.png" border="0" width="24" height="20" alt="First"></a>
                        <a class="navbutton" href=""><img src="/includes/images/btn_pag_prev.png" border="0" width="24" height="20" alt="Previous"></a> 
                        Page x of y
                        <a class="navbutton" href=""><img src="/includes/images/btn_pag_next.png" border="0" width="24" height="20" alt="Next"></a> 
                        <a class="navbutton" href=""><img src="/includes/images/btn_pag_last.png" border="0" width="24" height="20" alt="Last"></a>
                    </td>
                </tfoot>
Basically, I want to update the id to whatever page it is to load, and if clicked and the id > 0 then call the ajax script again with a page parameter. My current script doesn't separate button function, I know ... just trying to get some kind of sign that the event is being fired.

Anyhow, it's late, and this isn't going to play ball for me tonight. Any more help here would be great.

Cheers
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: AJAX - update table and selects

Post by pickle »

If code is injected into the page via AJAX (and therefore after page load & the DOM is ready), then jQuery doesn't listen to it. You need to have that navbutton.click listening code in the same scope as the code that injects the pagination into the page.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Re: AJAX - update table and selects

Post by Stryks »

That HTML section for the pagination is actually in the index page, not a part of the AJAX call. My thought was that if I could just update the ID for each button along with the 'page x of y' part using javascript, I wouldn't have to send new buttons with each table update, and therefore shouldn't have to reissue the event handler.

Maybe I'm thinking too far into this, but it just seems that if I define the event handler for the pagination controls under the table loader, then I'm going to be rewriting the pagination table loader inside the table loader? And if I do that, then wont I end up having to add another table loader under that to restart the event listeners again?

This is really frustrating. I can code PHP for hours without getting stuck or struggling to solve a problem, but I'm finding this mindbending. :?
Post Reply