Jump to content
Larry Ullman's Book Forums

QuakeLive

Members
  • Posts

    50
  • Joined

  • Last visited

  • Days Won

    1

Everything 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); });
  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. 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: But in the example tables.html (ch13) there CSS included is: and JavaScript included: ... 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. 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. 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. 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. 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. 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: 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: 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. 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: but for me it would be more logical (and nicer) to Make a Request first: Maybe there is some practical reason why...
  14. 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! So, speaking about the default behaviour - regardless of whether everything was OK - page somescript.php would be loaded.
  15. Thank you so much for the answers! 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? 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!!!
  16. 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... 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?
  17. 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? Sorry for bad English.
  18. 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: 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.
  19. 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!
  20. 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
  21. Ok ,I just added a missing single quotation mark. Here is how it looks now after clicking on the button: I did not understand this, I think that I have never used network panel that you are mentioning here.
  22. 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: 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...