Jump to content
Larry Ullman's Book Forums

QuakeLive

Members
  • Posts

    50
  • Joined

  • Last visited

  • Days Won

    1

Posts posted by QuakeLive

  1. EDIT: In the meantime I solved this - the answer is at the end

     

    Hi,

    First of all - I apologize - my English is bad.

    I have this JSON data in file mydata.json:

    [
      {"name": "Aster", "product": "aster", "stock": "10", "price": "2.99"},
      {"name":"Daffodil","product":"daffodil","stock":"12","price":"1.99"},
      {"name":"Rose","product":"rose","stock":"2","price":"4.99"},
      {"name":"Peony","product":"peony","stock":"0","price":"1.50"},
      {"name":"Primula","product":"primula","stock":"1","price":"3.12"},
      {"name":"Snowdrop","product":"snowdrop","stock":"15","price":"0.99"}
    ]
    

    I want to use this JSON to create the following HTML elements (using jQuery/Ajax):

    <div class="dcell">
          <img src="images/aster.png"/>
          <label for="aster">Aster:</label>
          <input type="text" id="aster" name="aster" value="0" stock="10" price="2.99" required>
    </div>
    <div class="dcell">
          <img src="images/daffodil.png"/>
          <label for="daffodil">Daffodil:</label>
          <input type="text" id="daffodil" name="daffodil" value="0" stock="12" price="1.99" required >
    </div>
    <div class="dcell">
          <img src="images/rose.png"/>
          <label for="rose">Rose:</label>
          <input type="text" id="rose" name="rose" value="0" stock="2" price="4.99" required>
    </div>  
    <div class="dcell">     
          <img src="images/peony.png"/>
          <label for="peony">Peony:</label>
          <input type="text" id="peony" name="peony" value="0" stock="0" price="1.50" required>
    </div>
    <div class="dcell">
          <img src="images/primula.png"/>
          <label for="primula">Primula:</label>
          <input type="text" id="primula" name="primula" value="0" stock="1" price="3.12" required >
    </div>
    <div class="dcell">
          <img src="images/snowdrop.png"/>
          <label for="snowdrop">Snowdrop:</label>
          <input type="text" id="snowdrop" name="snowdrop" value="0" stock="15" price="0.99" required>
    </div>            
    

    but I'm not sure how to solve this problem (using jQuery/Ajax).  

     

    I started this:

    <script type="text/javascript">
        $(function() {
            $("<button>Ajax</button>").appendTo("#buttonDiv").click(function(e) {
                $.getJSON("mydata.json", function(data) {
                      ///??????????????????????????????
                });
                e.preventDefault();
            });
        });
    </script>
    

    ... and I don't know how to do it. :(

     

    Do you know how I could do this, is there a simple and elegant way to do this

     

    Thank you in advance!

     

     

     

     

    Solution (it's so easy // embarrassed):

        $.getJSON("mydata.json", function(data) {
            var html = '';
            $.each(data, function(key, value){
                html += '<div class="dcell">';
                html += '<img src="images/'+value.product+'.png"/>';
                html += '<label for="'+value.product+'">'+value.name+':</label>';
                html += '<input type="text" id="'+value.product+'" name="'+value.product+'" value="0" stock="'+value.stock+'" price="'+value.price+'" required>';
                html += '</div>';
            });
        $('#yourContainerId').html(html);
        });
    
    • Upvote 1
  2. Hi,

     

    I plan to start learning PHP in the next two months (right now I'm learning some other things, and when I finish with them I'll start with PHP).

     

    I'm interested in this book, but I have one question - since the book is from 2011/2012, were there any major changes in the meantime? I mean, now we have newer version of PHP, so will I miss something "big" if I read book that is from 2011/12?

     

    If so, can we expect a new edition of this book in the near future?

     

    I apologize, my English isn't good.

     

     

  3.  

    Now, the tricky part has to do with the value of i. You would think that the value of i within the anonymous function would be equal to the value of i at the time the anonymous function is assigned to the onclick event handler. However, it's not.

    After the for loop is executed, the value of i is equal to the length of the trs array. For example, if there are five elements in trs, then i is equal to 5. This is the value that is retained in i when a tr element is clicked on. This happens because the anonymous function assigned to the onclick event handler is not called when the page is first loaded and the script is executed, but asynchronously at a later time when a tr element is clicked on; and at that later time, i is equal to the length of the trs array, as defined by our for loop logic.

    As such, if you use trs within the onclick event handler function, then you're really saying trs[5], which doesn't actually exist, thus causing an error.

    This explains it! I have to think more, I have no concentration!  Thank you so much Hartley!

    Now I'm reading the chapter about Closures which is at the end of the book, where this is also explained :)

  4. Hi HartleySan,

     

    Sorry for the late reply. I was looking at code and I can't find what is the problem. I will upload original files from ch13 (also available here), and the same files but with added jquery.dataTables.min.js in js directory.

     

    1. Original (from larryullman.com & wihtout jquery.dataTables.min.js in js directory) - http://download1348.mediafire.com/k8eh0h0n78wg/hpe52nx7c4d52qp/ch13.zip

     

    2. With jquery.dataTables.min.js in js directory - http://download1072.mediafire.com/2rr2ohn9d3jg/0890rotur5egm89/withJS.zip

     

    This is not an emergency, when you have a lot of free time and will - you can check this  :)  And, sorry for my bad English.

    Thanks.

  5. Hi,

     

    In chapter 13 there is an example of using the DataTables plugin - in folder ch13 there is table.html.

     

    In that .html file there is: <script src="js/jquery.dataTables.min.js"></script>, but in js folder there is no that file. So, I downloaded the DataTables from http://datatables.net/download/, and in folder DataTables-1.10.0\media\js there is that file, so I just copied it (jquery.dataTables.min.js) to js folder of that example (ch13\js), but it doesn't work again :/

     

    Do you know what could be the problem?

     

    Also, I have another question - according to the documentation: http://datatables.net/manual/installation - to use DataTables we need to include DataTables on your page using the following HTML:

     

    <!-- DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="/DataTables-1.10.0/css/jquery.dataTables.css">
     
    <!-- jQuery -->
    <script type="text/javascript" charset="utf8" src="/DataTables-1.10.0/js/jquery.js"></script>
     
    <!-- DataTables -->
    <script type="text/javascript" charset="utf8" src="/DataTables-1.10.0/js/jquery.dataTables.js"></script>

     

    But in the example tables.html (ch13) there CSS included is:

     

    <link rel="stylesheet" href="css/demo_table_jui.css">

     

     

    and JavaScript included:

     

     

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <script src="js/jquery.dataTables.min.js"></script>

     

    ... which is different than in the documentation. Does this mean that I do not need to include CSS file jquery.dataTables.css as in documentation?

     

     

    EDIT: I also tested version of table.html with includes as it is explained in the documentation, but it still doesn't work :/

  6. Yes, I agree that the hardest step in programming is to go from copying examples in books to actually applying that knowledge.

    I remember that that took a while for me as well. Once you get there though, it's very satisfying and worthwhile.

    All I can really say is that if you keep at it, you'll get there. Certainly, it can be grueling at times, but that's the way it is with anything, I think.

     

    As for practicing with lots of examples vs. reading books, I think I'm in the middle, with perhaps more of an emphasis on doing rather than reading. Certainly though, everyone has their own way of learning.

    Just personally, when I approach something new, I like to read just a little bit to get me started, and after that, I like to run with it for a while, trying different things, and then once I have the basics down, I like to go back and read a lot more to better educate myself and learn the details.

     

    I am learning very slowly, I have a feeling it will take me 100...00 years  to read the books, to practice, to do the examples... Just now (today), I found this interesting video

     

     

    :)

  7. Don't be too hard on yourself. The gotcha you stumbled across has fooled many people, many times.

    If you already understand it though, that's great.

     

    I think the problem is not to understand, but to apply knowledge. In many cases, when I read this JS book or some JS tutorial - I can understand but when I want to apply knowledge and create something new and original - I just stuck, block... Of course, the key is to practice and gain experience. There are those who argue that programming should be learned "only through hundreds of examples and exercises, not through reading "fat books"... they claim that reading those books is a waste of time... But I personally do not believe in such stories, or I just don't have the capacity to learn in that way.

  8. Now, the tricky part has to do with the value of i. You would think that the value of i within the anonymous function would be equal to the value of i at the time the anonymous function is assigned to the onclick event handler. However, it's not.

    After the for loop is executed, the value of i is equal to the length of the trs array. For example, if there are five elements in trs, then i is equal to 5. This is the value that is retained in i when a tr element is clicked on. This happens because the anonymous function assigned to the onclick event handler is not called when the page is first loaded and the script is executed, but asynchronously at a later time when a tr element is clicked on; and at that later time, i is equal to the length of the trs array, as defined by our for loop logic.

    As such, if you use trs within the onclick event handler function, then you're really saying trs[5], which doesn't actually exist, thus causing an error.

     

    This explains it! I have to think more, I have no concentration! :) Thank you so much Hartley!

  9. Thank you very much HartleySan!!!
     
     
     
    I tested your code and it works perfectly!
     
    Right now, I'm making version with external .js files. After that, I'll try to make some CSS, for example - row for the current CD will have a different color... : )
     
    I must say that I knew that code from my post is bad - but I didn't know why exactly... After seeing your code and explanations, it's clear now.
     
    There are a few interesting things regarding your code:
     

    currentCd = (currentCd - 1 + numCds) % numCds;
    

    I must say that I never would have thought to do it this way. Very clever : )
     
    The best way to understand this is to do a few examples, for example:
     
    Lets say that the number of CDs are 5, and that the currently selected CD is third (currentCd  = 2):
     

    numCds = 5

    currentCd  = 2

     

    To get the previous CD:
     

    (2 - 1 + 5) % 5  ---> 6 % 5 = 1 // which is the second CD

     

    If the current CD is 0:
     

    (0 - 1 + 5) % 5 --->4 % 5 = 4 // which is the fifth CD

     
     
    There is one small mistake when typing, instead of cds[currentCd].years it should be cds[currentCd].year:
     

    html = '<ul><li>Artist: ' + cds[currentCd].artist + '</li><li>Title: ' + cds[currentCd].title + '</li><li>Year: ' + cds[currentCd].year + '</li></ul>';
              
    

     
     
    :)
     
     
    This is also very interesting:
     

    	for (i = 0, len = trs.length; i < len; i++) {
    		trs[i].onclick = function() {
    			currentCd = parseInt(this.id.split('_')[1], 10);
    			html = '<ul><li>Artist: ' + cds[currentCd].artist + '</li><li>Title: ' + cds[currentCd].title + '</li><li>Year: ' + cds[currentCd].year + '</li></ul>';
    			document.getElementById('cd_details').innerHTML = html;
    		};
    	}	
    

     
    First of all, I was thinking to do it in a completely different (*stupid) way... This way is elegant and short.
     
    As for this line:
     

    currentCd = parseInt(this.id.split('_')[1], 10);
    

     
    this.id - this is the value of id attribute of a row trs - but I'm not sure if I understood well this. "this" refers to an element on which onclick event happened, right? Why does not work this way:
     

    currentCd = parseInt(trs.id.split('_')[1], 10);

     
    ?
     
    Again, thank you very much HartleySan!!!

  10. QuakeLive, I don't mind offering you more pointed guidance/help/code, but if I do, I feel the need to pretty much rewrite all of your code. if you're okay with that and you still want more help, please let me know.

    Thanks.

    Thank you HartleySan! I would be grateful if you could help me to "fix" this, but, of course, this isn't urgent - when you have the will and some time :)

  11. I'm tempted to critique your HTML and JS, but aside from that, one thing I would strongly recommend is using JSON instead of XML.

    XML does have some advantages over JSON, but nowadays, JSON is pretty much the default standard, especially when you're consuming data on the JS side.

     

    To answer your question though, after outputting the table markup to the DOM, I would add an onclick event handler to all of the tr elements in the table. From there, you can determine which tr was clicked on, and display the appropriate CD data accordingly.

     

    First of all, I apologize for the delay in my reply. Now I'm trying to make it work, but without success and I give up. Some things work, but - as you noticed - HTML/JS code is very bad. As for the using of JSON instead of XML - now I will start reading/learning JSON :)

     

    Thanks!

  12. Hi,

     

    I started reading the chapter about Ajax (JavaScript and XML), but I wanted to learn little more about XML so I am also reading w3schools.com.

     

    There are good examples and tutorials, but I don't like some things such as using inline event handlers.

     

    Anyway, I wanted to create the following application:

     

     

    jq2p03.jpg

     

     

    My English is not good, but I'll try to explain how this application should work (there are two very similar examples on w3schools, and this example is a combination of these two. Also, I am not using inline event handlers and JavaScript is in external .js files, not in the HTML file)

     

     

    First of all, we have one XML file that looks like this:

    <CATALOG>
    	<CD>
    		<TITLE>Hide your heart</TITLE>
    		<ARTIST>Bonnie Tyler</ARTIST>
    		<COUNTRY>UK</COUNTRY>
    		<COMPANY>CBS Records</COMPANY>
    		<PRICE>9.90</PRICE>
    		<YEAR>1988</YEAR>
    	</CD>
    	<CD>
    		<TITLE>Greatest Hits</TITLE>
    		<ARTIST>Dolly Parton</ARTIST>
    		<COUNTRY>USA</COUNTRY>
    		<COMPANY>RCA</COMPANY>
    		<PRICE>9.90</PRICE>
    		<YEAR>1982</YEAR>
    	</CD>
    	<CD>
    		<TITLE>Still got the blues</TITLE>
    		<ARTIST>Gary Moore</ARTIST>
    		<COUNTRY>UK</COUNTRY>
    		<COMPANY>Virgin records</COMPANY>
    		<PRICE>10.20</PRICE>
    		<YEAR>1990</YEAR>
    	</CD>
    	<CD>
    		<TITLE>One night only</TITLE>
    		<ARTIST>Bee Gees</ARTIST>
    		<COUNTRY>UK</COUNTRY>
    		<COMPANY>Polydor</COMPANY>
    		<PRICE>10.90</PRICE>
    		<YEAR>1998</YEAR>
    	</CD>
    </CATALOG>
    

    This is the HTML file:

    <!doctype html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>XML Aplikacija - Katalog</title>
    	</head>
    	<body>
    		<div id="showCD"></div>
    		<br>
    		<input id="previous" type="button" value="<<" />
    		<input id="next" type="button" value=">>" />
    		<br><br>
    		<div id="tabela"></div>
    		<script src="js/ajax.js"></script>
    		<script src="js/xmlAplikacija.js"></script>
    	</body>
    </html>
    

    We have two buttons for navigation between the CDs (next and previous). For example, when you click on ">>" (next) - above (inside of <div id="showCD"></div>) will show some information (Artist, Title, Year) about the CD.

     

    Also, there is <div id="tabela"></div> - inside this will be displayed a table containing information about Artist and Title for ALL CDs  from XML (see picture above).

     

    There is one more thing - when you click on some row in that table - above the buttons, also inside of <div id="showCD"></div> need to show information about the CD (Artist, Title, Year) (same as with buttons, but instead of changing to the Next/Previous CD - you directly choose from a table by clicking on a row).

     

     

     

    So, let's see JavaScript:

     

    First, we have a standard ajax.js:

    function getXMLHttpRequestObject() {
    	var ajax = null;
    	if (window.XMLHttpRequest) {
    		ajax = new XMLHttpRequest();
    	} else if (window.ActiveXObject) {
    		ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
    	}
    	return ajax;
    }
    

    Then we have xmlAplikacija.js:

    window.onload = function() {
    	
    	var xmlhttp = getXMLHttpRequestObject();
    	var xmlDoc = null;
    	xmlhttp.onreadystatechange = function() {
    		if (xmlhttp.readyState == 4) {
    			if ((xmlhttp.status >= 200 && xmlhttp.status < 300) || (xmlhttp.status == 304)) {
    				xmlDoc = xmlhttp.responseXML;
    				
    				x = xmlDoc.getElementsByTagName("CD");
    				i = 0;
    	
    				function displayCD(i) {
    					artist = (x[i].getElementsByTagName('ARTIST')[0].childNodes[0].nodeValue);
    					title = (x[i].getElementsByTagName('TITLE')[0].childNodes[0].nodeValue);
    					year = (x[i].getElementsByTagName('YEAR')[0].childNodes[0].nodeValue);
    					txt = "Artist: " + artist + "<br>Title: " + title + "<br>Year: " + year;
    					document.getElementById('showCD').innerHTML = txt;
    				};
    				
    				displayCD(i);
    				
    				document.getElementById('previous').onclick = function() {
    					if (i > 0) {
    						i--;
    						displayCD(i);
    					}
    				};
    				
    				document.getElementById('next').onclick = function() {
    					if (i < x.length - 1) {
    						i++;
    						displayCD(i);
    					}
    				};
    				
    				var tbl = "<table border='1'>";
    				for (var b=0; b < x.length; b++) {
    					tbl += "<tr onclick='displayCD(" + b + ")'>";
    					tbl += "<td>";
    					tbl += x[b].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue;
    					tbl += "</td><td>";
    					tbl += x[b].getElementsByTagName('TITLE')[0].childNodes[0].nodeValue;
    					tbl += "</td></tr>";
    				};
    				tbl += "</table>";
    				document.getElementById('tabela').innerHTML = tbl;
    				
    			} else {
    				alert('Doslo je do greske');
    			}
    		}
    	};
    	xmlhttp.open('GET', 'resources/xmlFajl.xml', true);
    	xmlhttp.send(null);	
    };
    

    Everything works fine:

     

    jq2p03.jpg

     

    when I click on the buttons - it changes to the next/previous CD, there is a table with all CD-s.

     

    BUT, I don't know how to make it work - to change (show) CD when you click on a row. For example, when you click on "Dolly Parton" in that table - above should show (also inside of <div id="showCD"></div>) information about the CD (Artist, Title, Year) (same as with buttons, but instead of changing to the Next/Previous CD - you directly choose from a table by clicking on a row - as I have already explaine).

     

    On w3schools they wre using inline event handlers, and, as you can see in the code above - I've tried that:

    				var tbl = "<table border='1'>";
    				for (var b=0; b < x.length; b++) {
    					tbl += "<tr onclick='displayCD(" + b + ")'>";
    					tbl += "<td>";
    					tbl += x[b].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue;
    					tbl += "</td><td>";
    					tbl += x[b].getElementsByTagName('TITLE')[0].childNodes[0].nodeValue;
    					tbl += "</td></tr>";
    				};
    				tbl += "</table>";
    				document.getElementById('tabela').innerHTML = tbl;
    

    but without success, it doesn't work.

     

    Do you have any idea how this could work?

     

    Thanks in advance!

  13. As a general rule, you should always have event handlers set up before any events can fire that would trigger those events. Likewise, I would make sure that the onreadystatechange event handler is set up before you call the send method.

     

    Also, while my memory is a bit fuzzy, I seem to recall IE6 having issues if you do onreadystatechange last.

    Thank you!

  14. Is it important to Identify a Result Handler first, and then to Make a Request, or it does not matter? I am asking this because in the book Larry always first Identify a Result Handler and then Make a Request... for example:

     

     

    window.onload = function() {
        'use strict';
        var ajax = getXMLHttpRequestObject();

        ajax.onreadystatechange = function() {
            if (ajax.readyState == 4) {
                if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)) {
                    document.getElementById('output').innerHTML = ajax.responseText;
                } else {
                    document.getElementById('output').innerHTML = 'Error:' + ajax.statusText;
                }
            }
        };

        document.getElementById('btn').onclick = function() {
            ajax.open('GET', 'resources/test.txt', true);
            ajax.send(null);
        };

    };

     

    but for me it would be more logical (and nicer) to Make a Request first:

     

     

    window.onload = function() {
        'use strict';
        var ajax = getXMLHttpRequestObject();

        document.getElementById('btn').onclick = function() {
            ajax.open('GET', 'resources/test.txt', true);
            ajax.send(null);
        };

        ajax.onreadystatechange = function() {
            if (ajax.readyState == 4) {
                if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)) {
                    document.getElementById('output').innerHTML = ajax.responseText;
                } else {
                    document.getElementById('output').innerHTML = 'Error:' + ajax.statusText;
                }
            }
        };

    };

     

    Maybe there is some practical reason why... :huh:

  15. HartleySan, thank you so much for helping me to understand Ajax, JavaScript... now, some things are much clearer. Thank you for your support and help!

     

     

    As for the form question, the form will submit to something/somescript.php, and unless you redirect the user back to example.html after that, you will not see example.html again. That make sense.

     

    So, speaking about the default behaviour - regardless of whether everything was OK - page somescript.php would be loaded.

  16. Thank you so much for the answers!
     

    As for checking whether a user name exists without Ajax and without reloading the page, the only way to do that is to get the entire DB of user names on page load, store that in a JS object, and then check from there. If you have < 500 users or so, that might be doable. In most practical cases though, you should never do that.

     

    1. So, it is possible that client JavaScript communicate with DB, or that would be done (somehow) with php or with some other server-side language which would store all the names from DB in JavaScript object?

     

    I understood that I should never do that, I'm just asking because I want to make some things in my head as clear as possible. :)

     

    2. I'm not sure if I'll formulate well this question - is Ajax the only way for JavaScript to "read" the content of other files such as text files? In this topic we had an example where JavaScript actually "read" the content of text file test.txt, and put it on html page "test.html". That was done by using open method and responseText property (by using the "Ajax technology"):

     

    ajax.open('GET', 'resources/test.txt', true);

    ...

    ...

    document.getElementById('output').innerHTML = ajax.responseText;

     

    Also, can JavaScript write to some files?

     

     

    If the action value is the same as the current script, then the current script is reloaded. Otherwise, a different script is loaded. In all cases, the default behavior does cause a page reload.

     

    I'm not sure if understood this well. Let's say that we have some simple html file named example.html with some registration form:

     

    ...

    <form ... action="something/somescript.php">

    ...

     

    The default behavior of a form is to submit to that script ("something/somescript.php") and example.html (the same page) will be reloaded?

     

    So, the action value is something/somescript.php, but what do you mean by the "current script"?

     

    Thank you very much again!!!

  17. It's up to you.

    The problem with onblur is that it could potentially be fired many times during a single form submission, which can lead to a bigger load on the server.

    Really, there are many ways you can approach this: Use a key event, a blur event, a submit event, etc.

     

    Based on what I've read until now, I suppose that Ajax search works based on onkeypress event... but my knowledge isn't enough, I'm a beginner, so maybe I'm wrong...

     

     

    Also, I agree that you don't need Ajax for the onsubmit event. I wasn't suggesting that you do use Ajax. I was suggesting that you prevent the default form submission so that you could do some basic checks on the client-side before submitting the form.

    Doing so involves the use of JavaScript, but not Ajax.

     

    Regarding the previous example, is it possible to check that "username" already exists without reloading page and without Ajax?

     

    I'm still learning JavaScript and I don't know any of server-side languages such as PHP, but if I understood some things well - when we submit some form - we actually forward the entered data to a server-side script that is in <form ... action="somescript.php"> and then the page is reloaded. That is the default behaviour, right? And, if we are speaking about the default behaviour - does it mean that the same page is reloaded?

     

    If we want to check that username already exists without reloading page and without Ajax - we need to prevent the default behaviour. But, in that case, is it possible to forward the entered data to a server-side script and to get the results of validation without the default behaviour - reloading the page again?

  18. The onsubmit event is often used to perform simple validation on the client-side to catch obvious errors. This is beneficial because you don't have to submit the form to the server-side and reload the page if there is an error that client-side validation catches.

    This creates a much smoother experience for the user, and it lessens the load on the server, which is always a good thing.

     

    The golden rule of client-side validation though is that you should never rely solely on it. I like to use client-side validation for very simple things, but regardless, I always perform full and thorough validation on the server-side (including repeating the checks I do on the client-side).

    Would not it be better to use, for example, onblur event for every field, so if someone enters username that already exists, he will know that as soon as onblur event happens for that field?

     

    As for the onsubmit event - in that case - do we really need Ajax because we can just prevent the default browser behaviour and not reload the page and show errors, right? :huh:

     

    Sorry for bad English.

  19. Hi,

     

    First of all, my English is very bad, but I hope you will understand me.

     

    I started reading the chapter 11 (Ajax) and, at some points, I think that understood well, but there is one example that confuses me. Let's look at an example from the beginning of the book:

     

    ... When the user clicks the submit button, the JavaScript could pause the submission of the form and send the form data to a server-side script. That script would perform all of the validation and return data that indicates a simple status or a list of errors. If errors were returned, the JavaScript would parse the errors and update the page, indicating any and all errors accordingly, and add highlighting to further emphasize the problems. If the returned status indicated that no errors occurred, the JavaScript would do whatever to move the user along in the process...

     

     

     

    2n9jqjt.jpg

     

     

     

    I didn't really understand the purpose of this. If AJAX was used when user fills some fields like username, that would make sense. For example, when user enters username and onblur event happens - than AJAX will be used to "do the job" and that would save some time for that user if he entered username that already exists. And that makes sense.

     

    But, it this example, AJAX is used on submit. So, what the difference between using AJAX on submit and using some server script (<form ... action="script.php">) to validate data? In both cases, the user must press the button and see if he entered everything ok.

  20. I tested your code, and it works fine.

    I think the big issue though is that you're trying to Ajax-request a file using the file:// protocol. In other words, you're not running the request through a server.

     

    Try starting up XAMPP, or whatever web server you use, and run the script through that. You should be fine.

    Sorry, that was a problem. I was thinking that XAMPP (apache) was needed only for server side scripts such as PHP, but now I see that it must be used because of HTTP protocol. Sorry again.

     

    Thanks!

  21. I tested with different .txt. files and it's always the same error. Also, Chrome is saying something else (the picture above in my previous post), but I don't understand it because .js code looks fine... ?

     

    test.html:

    <!doctype html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>Testing Ajax</title>
    		<link rel="stylesheet" href="css/clean.css">
    	</head>
    	<body>
    		<h1>Ajax Test</h1>
    		<div><button type="button" id="btn">Run the test</button><br>
    			<p id="output"></p>
    		</div>
    		<script src="js/ajax.js"></script>
    		<script src="js/test.js"></script>
    	</body>
    </html>
    

    js/ajax.js:

    function getXMLHttpRequestObject() {
    	var ajax = null;
    	if (window.XMLHttpRequest) {
    		ajax = new XMLHttpRequest();
    	} else if (window.ActiveXObject) {
    		ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
    	}
    	return ajax;
    }
    

    js/test.js:

    window.onload = function() {
    	'use strict';
    	var ajax = getXMLHttpRequestObject();
    	ajax.onreadystatechange = function() {
    		if (ajax.readyState == 4) {
    			if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)) {
    				document.getElementById('output').innerHTML = ajax.responseText;
    			} else {
    				document.getElementById('output').innerHTML = 'Error:' + ajax.statusText;
    			}
    		}
    	};
    	document.getElementById('btn').onclick = function() {
    		ajax.open('GET', 'resources/test.txt', true);
    		ajax.send(null);
    	};
    };
    	
    

    ... and there is a text file: resources/test.txt

  22. Chrome (my personal preference) and other browsers have a network panel that allows you to view all outgoing requests and responses. In Chrome, the network panel is within the dev tools. If you don't know how to use the Chrome dev tools, please Google it. They are essential for any serious front-end work.

     

    Once you're in the network panel, make the Ajax request, and you'll see it logged with all of the details.

    Please let us know if you see any errors in there. Also, check the console in the dev tools, and let us know if there are any JS syntax errors in there.

     

    Thanks.

    2s66nw8.jpg

  23. Ok ,I just added a missing single quotation mark.

     

    Here is how it looks now after clicking on the button:

     

    f52l2c.jpg

     

    What about the network panel? What info shows up there for the Ajax request?

    I did not understand this, I think that I have never used network panel that you are mentioning here. :unsure:

  24. Hi,

     

    I can not figure out why the first example does not work. Also, I downloaded and tested code from this site - and it does not work...

     

    This example starts on page 433:

     

     

    To test the information covered so far, this next example will simply request a resource and write the received response to the page (Figure 11.1). The relevant HTML is: fiGURe 11 1 The content shown below the button will be retrieved from another file via Ajax.

     

    <div><button type=”button” id=”btn”>Run the test</button><br>
    <p id=”output”></p></div>

     

    I would put this in a file named test.html, which would include both the ajax. js script (the contents of which were just shown) and then test.js, to be written in the following steps. You’ll also need to create a plain text file named test.txt, and you can place any amount of HTML or text in it. Store this text file in a resources directory, to keep it separate from the other files

     

    Here is my ajax.js:

    function getXMLHttpRequestObject() {
    	var ajax = null;
    	if (window.XMLHttpRequest) {
    		ajax = new XMLHttpRequest();
    	} else if (window.ActiveXObject) {
    		ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
    	}
    	return ajax;
    }
    

    Here is my test.js:

    window.onload = function() {
    	'use strict';
    	var ajax = getXMLHttpRequestObject();
    	ajax.onreadystatechange = function() {
    		if (ajax.readyState == 4) {
    			if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)) {
    				document.getElementById('output').innerHTML = ajax.responseText;
    			} else {
    				document.getElementById('output').innerHTML = 'Error: + ajax.statusText;
    			}
    		}
    	};
    	document.getElementById('btn').onclick = function() {
    		ajax.open('GET', 'resources/test.txt', true);
    		ajax.send(null);
    	};
    };
    

    Also, there is some text file in resources/test.txt...

     

    And it does not work (tested on Firefox, Opera, IE, Chrome). The same is with code downloaded form this site - when I click on button - nothing happens.

     

    Do you know what could be the problem?

     

    Thanks in advance!

×
×
  • Create New...