Ajax Example

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • iam_clint
    Recognized Expert Top Contributor
    • Jul 2006
    • 1207

    Ajax Example

    AJAX Basic Example
    [CODE=javascript]
    <script>
    //set the variables.
    function getArticle(id) {
    var link = "/getNews.asp";
    xmlhttpPost(lin k, id);
    }

    //Make the actual connection.
    function xmlhttpPost(str URL, id) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttp Request) {
    self.xmlHttpReq = new XMLHttpRequest( );
    }
    // IE
    else if (window.ActiveX Object) {
    self.xmlHttpReq = new ActiveXObject(" Microsoft.XMLHT TP");
    }
    self.xmlHttpReq .open('POST', strURL, true);
    self.xmlHttpReq .setRequestHead er('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq .onreadystatech ange = function() {
    if (self.xmlHttpRe q.readyState == 4) { //ready state 4 means its complete.
    updatepage(self .xmlHttpReq.res ponseText);
    }
    }
    self.xmlHttpReq .send(getquerys tring(id));
    }

    //set the query string to be sent
    function getquerystring( id) {
    qstr = 'data=' + escape(id); // NOTE: no '?' before querystring
    return qstr;
    }

    //put the data on the page.
    function updatepage(str) {
    document.getEle mentById("data" ).innerHTML = str;
    }
    </script>
    <select onchange="getAr ticle(this.valu e);">
    <option value="1">Train hits car</option>
    <option value="2">Airpl ane Crashes</option>
    <option value="3">Menta l Health</option>
    </select>
    <div id="data"></div>
    [/CODE]


    Now for the getNews.asp --- not fully functional code but an example
    [CODE=ASP]
    <%
    news_id = request("id")
    strSQL = "select * from news where news_id = " & new_id
    rs.open strSQL, connection, 1, 1
    if not rs.eof then
    response.write rs("story")
    end if
    %>
    [/CODE]
  • herocks
    New Member
    • Jun 2007
    • 5

    #2
    Mind saying what the code dose?

    Comment

    • iam_clint
      Recognized Expert Top Contributor
      • Jul 2006
      • 1207

      #3
      it does an ajax query.

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        Originally posted by herocks
        Mind saying what the code dose?
        It gets the news articles from a database by selecting from a drop down without having to refresh/reload the page.

        If you don't know Ajax is, maybe you should check out some tutorials.

        Comment

        • herocks
          New Member
          • Jun 2007
          • 5

          #5
          Sorry for my noobness. I looked at some AJAX tutorials and this makes a lot more sense but a few things I still don't get...

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            Originally posted by herocks
            Sorry for my noobness. I looked at some AJAX tutorials and this makes a lot more sense but a few things I still don't get...
            Like ?

            Comment

            • herocks
              New Member
              • Jun 2007
              • 5

              #7
              Eh, I just needa study the code more...

              Comment

              • cheogt
                New Member
                • Oct 2007
                • 5

                #8
                [CODE=javascript]ajax=function(s trURL,sSend){
                var xmlHttpReq=fals e
                var self=this
                if (window.XMLHttp Request)self.xm lHttpReq=new XMLHttpRequest( )
                else if(window.Activ eXObject)self.x mlHttpReq=new ActiveXObject(" Microsoft.XMLHT TP")
                self.xmlHttpReq .open('POST',st rURL,false)
                self.xmlHttpReq .setRequestHead er('Content-Type', 'application/x-www-form-urlencoded')
                self.xmlHttpReq .onreadystatech ange=function() {
                if (self.xmlHttpRe q.readyState==4 ){
                ajax.resul=self .xmlHttpReq
                }
                }
                self.xmlHttpReq .send(sSend)
                }
                [/CODE]Hello i have made a little change on the main function, so you can use it like this:
                [CODE=javascript]function getArticle(id){
                ajax('dataExamp le.php',id) // php,asp,...
                alert(ajax.resu l.responseText)
                }
                [/CODE]Not a big deal but now you can use the data loaded directly with the javascript, and no need to load the data into a div continer, i hope it can be helpfull
                Last edited by acoder; Oct 31 '07, 04:10 PM. Reason: Added code tags

                Comment

                • cheogt
                  New Member
                  • Oct 2007
                  • 5

                  #9
                  Sorry o forgot to tell that i couldn't make it work with Firefox, it works only with ie, if some one find a way.. please :)

                  Comment

                  • acoder
                    Recognized Expert MVP
                    • Nov 2006
                    • 16032

                    #10
                    Originally posted by cheogt
                    Sorry o forgot to tell that i couldn't make it work with Firefox, it works only with ie, if some one find a way.. please :)
                    ajax.resul.resp onseText is only available after the readyState is 4, so the call must be made within the anonymous function onreadystatecha nge or a function within that anon. function.

                    Comment

                    • eragon
                      Contributor
                      • Mar 2007
                      • 431

                      #11
                      could somebody make a firefox compatable versoin? i officially threw out internet explorer. completely. gone. so sad. more secure. Yay Firefox!!!!!

                      Comment

                      • iam_clint
                        Recognized Expert Top Contributor
                        • Jul 2006
                        • 1207

                        #12
                        i'm pretty sure my example works in firefox.

                        Comment

                        • gits
                          Recognized Expert Moderator Expert
                          • May 2007
                          • 5390

                          #13
                          ok ... let's fix the adapted code ... and a note: the original posted code in the article worked! ... but in case anybody wanted to use the adaptation we have to fix it the following way (for example):

                          first we adapt the ajax-function so that we may pass a callback to it, that may work with the request-response the correct way:

                          [CODE=javascript]var ajax = function(strURL , sSend, cb) {
                          var xmlHttpReq = false;
                          var self = this;

                          if (window.XMLHttp Request) {
                          self.xmlHttpReq = new XMLHttpRequest;
                          } else if (window.ActiveX Object) {
                          try {
                          xmlHttpReq = new ActiveXObject(' Msxml2.XMLHTTP' );
                          } catch (ex) {
                          try {
                          xmlHttpReq = new ActiveXObject(' Microsoft.XMLHT TP');
                          } catch (ex) {
                          }
                          }
                          }

                          self.xmlHttpReq .open('POST', strURL, false);
                          self.xmlHttpReq .setRequestHead er('Content-Type',
                          'application/x-www-form-urlencoded');

                          self.xmlHttpReq .onreadystatech ange = function(cb) {
                          if (self.xmlHttpRe q.readyState == 4) {
                          cb(self.xmlHttp Req);
                          }
                          }

                          // sSend is the id passed by getArticle later on ...
                          // build a query-string in case you need to use it
                          // i didn't do anything with it here
                          self.xmlHttpReq .send(sSend)
                          }
                          [/CODE]
                          later on the call should look like this:

                          [CODE=javascript]function getArticle(id) {
                          var cb = function(res) {
                          alert(res.respo nseText);
                          };

                          ajax('dataExamp le.php', id, cb);
                          }[/CODE]
                          kind regards

                          ps: and one more note to posters: please try to write the code in articles-sections a way more readable, use indentations, the var keywords etc. and use the semicolon to end your statements ... please! When adapting code then try not to post 'unready' code except you mark it as to be so.

                          Comment

                          • acoder
                            Recognized Expert MVP
                            • Nov 2006
                            • 16032

                            #14
                            Originally posted by iam_clint
                            i'm pretty sure my example works in firefox.
                            Yes it does, but I think eragon was probably referring to cheogt's adapted code.

                            Comment

                            • acoder
                              Recognized Expert MVP
                              • Nov 2006
                              • 16032

                              #15
                              Originally posted by eragon
                              could somebody make a firefox compatable versoin? i officially threw out internet explorer. completely. gone. so sad. more secure. Yay Firefox!!!!!
                              As pointed out, the original version in the first post does work in Firefox.

                              Even though you might hate Internet Explorer, it is still the most popular browser. You have no choice, but to support it (unless its a personal application which only you will use or all users will be using Firefox).

                              To help you, check out A Guide to Coding Cross-Browser Scripts and Browser Bugs, Quirks and Inconsistencies.

                              Comment

                              Working...