Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

javascript - Autorefreshing/updating table using jQuery ajax by either using json or html files

So @SOF,

I've been trying to make my webpage of school grades, results, projected grades... etc have an auto update feature so that the data on the page refreshes when new data comes through via the use of jquery and ajax aswell as have a "single view" for classes.

My main issue is that I'm unable to get any form of ajax refreshing/loading working correctly, I can produce my output in json or single html files, for my purposes I think the json would be better but I'm not sure.

My webpage has a navigation helper in the top left, which is a dropdown menu which is populated via a list found by a "search" for <a id="CLASS1" optionname="CLASS 1"></a> which can be found within the table, however if need be I can populate this outside of the table if need be.

I ideally want to be able to modify the dropdown so we have in this example a total of 8 options consisting of - Select Class -, Class 1, Class 2, Class 3, Class 4, Class 5, All Updating, All Non-Updating

All Updating

  • This option will load all the class's into one html viewable page and update each class every 30 seconds (I say each class as some classes might update in one hour, in a different hour some other classes might update) so it would need to compare and if different then update?

All Non-Updating

  • This option will load all the class's into one html viewable page but will not update unless the user clicks on a different class (using the dropdown) and then clicks back...

Class 1, Class 2, Class 3... etc (Individual Loading/Single View)

  • This option will load a single class's data into a html viewable page and will update that specific class every 30 seconds, in a previous post a user named Gaby aka G. Petrioli gave an example which is pretty close to what I need however the member never came back to me: http://jsfiddle.net/u7UkS/4/

Links to all the data

HTML - http://pastebin.com/raw.php?i=0PNQGMmn

CSS - http://pastebin.com/raw.php?i=4H5GHv15

JSON - http://pastebin.com/raw.php?i=xk860dBN

Single Class Page - http://pastebin.com/raw.php?i=HvpaVhG6

JSFiddle - http://jsfiddle.net/kHtuQ | http://jsfiddle.net/kHtuQ/show

Previous post with some ajax examples by certain members: Anchor Cycler / Dropdown to import school class data periodically


Below is an example to show roughly what is in each "class" Note Class = School Class

Super Slimed Down Table Example:

<table id="gradient-style">
    <tbody>
        <thead>
            <tr>
                <th scope="col"><a id="CLASS1" optionname="CLASS 1"></a>Class</th>
            </tr>
        </thead>
        <tr><td>Class 1</td></tr>
    </tbody>
    <tfoot>
            <tr>
                <th class="alt" colspan="34" scope="col"><a id="KEY"></a><img class="headimager" src="http://placehold.it/250x50"/></th>
            </tr>
            <tr>
                <td colspan="34"><em><b>Data</b> - Test</em></td>
            </tr>
    </tfoot>
</table>

If anyone could help with this it would be much appreciated and if you are able to comment please do so that I can continue to learn.

Thanks
Dennis S

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

using ajax is very simple,
I recommend you to use HTML datatype for this as you have a table in your container,
there is an api documentation here => http://api.jquery.com/jQuery.ajax/
here's a fiddle I made for you => http://jsfiddle.net/sijav/kHtuQ/19/ or http://fiddle.jshell.net/sijav/kHtuQ/19/show/

I have put ajax code in a function named updateClass(url) which url stands for the url to get and it will append the container with the HTML it get =>

function updateClass(url){
    $.ajax({
        url: url,
        dataType: "HTML",
        error: function(msg){
            alert(msg.statusText);
            return msg;
        },
        success: function(html){
            $("#container").html(html);
        }
    });
}

I have added a refreshClass which refresh the whole container class, =>

function refreshClass(){
            updateClass("http://fiddle.jshell.net/sijav/mQB5E/5/show/"); //update the class
}

and changed on change selector to below code =>

var classUpdateI; //stands for our interval updating class
$(".class-selector").on("change",function(){
    if (classUpdateI!=null)clearInterval(classUpdateI); //If the selector changed clear the interval so the container won't be update on it's own
    if(this.value == "")
        return; // if the value is null don't do anything
    else if(this.value == "allclassnup"){
        refreshClass(); //if the value is allclassnup which is stands for All Non-Updating just refresh the whole class 
    }
    else if(this.value == "allclassup"){
        refreshClass(); //if the value is allclassup which is stands for All Updating refresh the whole class and set an interval for thirty second (look for 30*1000)
        classUpdateI = setInterval(refreshClass,30*1000);
    }
    else //else then it's a simple class value, just simply update the current class
        updateClass(this.value);
})

Hope it helps ;)
EDIT: Edited so it can get big table (not generate it!) and all-updating will update in an interval of 30 sec
AnotherEDIT: Believe it or not I have done all of your question!
WORKING FIDDLE:http://jsfiddle.net/sijav/kHtuQ/39/ or http://fiddle.jshell.net/sijav/kHtuQ/39/show/
1 that is because it was only done for the last html, for the new we should make it again! so put the whole $('tr').click() function into another function and call it when necessary.
- do you want this to fully working? it's a little bit complicated but it can works with a bit of change in codes! that I'm gonna show you, Alright here's the algurithm we should put the current class on class selector change to cookie and then we can read it whenever we refresh or reload the page and put the necessary selected class and so on ...
but in code designing here I did to make it working,
first I made a global variable called FirstTimeInit = true; just to be sure if we're on the first time of page loading or not, second I put the for loop that make things highlighting on page load to a function called selectSelectedClass, why? because we need to call it many times, Third I added some if statement to be sure if we can read cookies then change highlighted things and current class also, here is the code:

if(readCookie("CurrentClass")) //if we can read coockie
    $(".class-selector").val(readCookie("CurrentClass")).change(); //change it's value to current cookie and trigger the change function
else{ // else
    selectSelectedClass(); //select those which was highlighted before
    trClick(); //make things clickable
    FirstTimeInit = false; //and turn of the first time init
}

Forth adding a create cookie on selector value changes = > createCookie("CurrentClass",$(".class-selector").val(),1);
and finally change the success on getting Ajax to this

        success: function(html){
            $("#container").html(html + '<a id="KEY"></a>'); //the html container changer with adding extra id , I'll explain it later it's for your second question
            if(FirstTimeInit){ //if it is First Time then
                selectSelectedClass(); //highlight which was highlighted after put the correct html
                FirstTimeInit = false; // turn of the first time init
            }
            else //else
                for (var i=0;i<($("table").children().length);i++){
                    if(readCookie(i))
                        eraseCookie(i); //erase every cookie that has been before because the table is now changed and we're going on another table so old cookie won't matter
                }
            trClick(); //make things selectable!
        }

Also to make it bugfree I have changed the refreshClass to turn firstinit when the selected class is all or it is null because then we have all classes and need those cookies! so here's the code:

function refreshClass(){
    if(readCookie("CurrentClass")=="allclassnup"||readCookie("CurrentClass")=="allclassup"||readCookie("CurrentClass")==null)
        FirstTimeInit = true;
    updateClass("http://fiddle.jshell.net/sijav/mQB5E/5/show/");
}

2 the <a id="TOP"></a> must be before the container, the <a id="KEY"></a> must be generated on the end of the container after putting html on the container. so $("#container").html(html + '<a id="KEY"></a>');

3 Next and Previous button was designed for non-ajax previous design, It's now needing a different solution! see these simple codes for example

$("#PreviousClass").click(function(){//on prev click
    $(".class-selector").val($(".class-selector option:selected").prev().val()).change() //change the value to the prev on and trigger the change
});

$("#NextClass").click(function () {//on next click
    $(".class-selector").val($(".class-selector option:selected").next().val()).change() //change the value to the prev on and trigger the change
});

4 Yes It is possible you should change your up to key and down to these codes and you're good to go =>

currentClass=0;
$("a.TOPJS").click(function () {
    if(currentClass>0){
        currentClass--
        scrollToAnchor('CLASS'+currentClass);
    }
});

$("a.KEYJS").click(function () {
    if($("a[id='CLASS" + currentClass + "']")[0]!=undefined){
        currentClass++
        scrollToAnchor('CLASS'+currentClass);
    }
    else
        scrollToAnchor('CLASSMAX');
});

Godd Luck

Another Request EDIT: (hope this will be the last!)
Working Fiddle: http://jsfiddle.net/sijav/kHtuQ/42/ or http://fiddle.jshell.net/sijav/kHtuQ/42/show/
alright as you didn't like the change class on refresh to one which was in it I have removed that, and a better I have added some codes to have classes in cookies, as cookies are not tree there is some kind of conditions, the class is being read from the last character of class selector so be sure to have class number at the last character like -> Class number ***5*** the number 5 will be read for class selector!
EDIT: optimize class next and prev see http://jsfiddle.net/sijav/kHtuQ/46/
EDIT: As per comment requested,
That is what I'm trying to tell you, sometimes the demo shows on jsfiddle.net, sometimes it shows on fiddle.jshell.net, these are different domains and you cannot get html from different domains.
1) You may only put function in Interval or just create another function and call it proper way like this =>

classUpdateI = setInterval(function(){updateClass(this.value,parseInt(a.charAt(a.length-1),10));},30*1000);

2) Missings?! I can't find your second question!
3) Well, ... trclick needs to change ... to =>

function trClick(tIndex){ //tIndex would be classnumber from now on
    if (tIndex == -1){ //if it is all updating or all non updating
        $("tr").click(function(){ //do the previous do
            $(this).toggleClass('selected').siblings().removeClass('selected');
            if(readCookie($(this).parent().index("tbody"))){
                if(readCookie($(this).parent().index("tbody"))==$(this).index())
                    eraseCookie($(this).parent().index("tbody"));
                else{
                    eraseCookie($(this).parent().index("tbody"));
                    createCookie($(this).parent().index("tbody"),$(this).index(),1);
                }
            }
            else
                createCookie($(this).parent().index("tbody"),$(this).index(),1);
        });
    }
    else{ //else
        $("tr").click(function(){ //on click
            $(this).toggleClass('selected').siblings().removeClass('selected');//do the toggle like before
            if(readCookie(tIndex)){ //if you can read the CLASS cookie, not the current index of table because our table has only one row
                if(readCookie(tIndex)==$(this).index()) //as before if we selecting it again
                    eraseCookie(tIndex); //just erase the cookie
                else{ //else
                    eraseCookie(tIndex); //select the new one
                    createCookie(tIndex,$(this).index(),1);
                }
            }
            else
                createCookie(tIndex,$(this).index(),1); //else if we can't read it, just make it!
        });
    }
}

and when we call it on Ajax success we should call it with classNumber => trClick(classNumber);
Last working fiddle: http://jsfiddle.net/sijav/kHtuQ/53/ or http://fiddle.jshell.net/sijav/kHtuQ/53/show/

Good Luck


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...