www.webdeveloper.com
Results 1 to 15 of 15

Thread: [RESOLVED] Javascript: using json file

  1. #1
    Join Date
    Jan 2018
    Posts
    11

    resolved [RESOLVED] Javascript: using json file

    at the calculation total price I get a nan, I think that from my jsonfile I have to read a number or convert a parsefloat. But I do not find it where. Can someone help me?

    Thank you.

    Code:
    onload = Initieer;
    var Gerechten;
    var Menus;
    var Naam;
    var Prijs;
    var Beschrijving;
    var Foto;
    var Gangen;
    var Aantal;
    var knop;
    var Main;
    var InBestelling = [];
    var AantalPers = [];
    var SoortGang = [];
    var GekozenGang;
    var GeselecteerdeMenu;
    var AantalPersonen;
    var Afrekenen = 0;
    
    function Initieer() {
        Naam = document.getElementById('naamGerecht');
        Prijs = document.getElementById('prijsGerecht');
        Beschrijving = document.getElementById('beschrijvingGerecht');
        Foto = document.getElementById('afbGerechje');
        Gangen = document.getElementById('hoofd');
        Menus = document.getElementById('sub');
        Aantal = document.getElementById('aantal');
        knop = document.getElementById('knop');
        Main = document.getElementById('main');
    
        var xmlhttp = new XMLHttpRequest();
        var plaats = "JSON/Gerechten.json";
    
        xmlhttp.onreadystatechange = function () {
            if (this.readyState === 4 && this.status == 200) {
                Gangen.addEventListener('change', Wijzigen, false);
                Menus.addEventListener('change', Updaten, false);
                knop.addEventListener('click', Bestel, false);
                Gerechten = JSON.parse(this.responseText);
                VulGegevensIn();
            }
        };
        xmlhttp.open('GET', plaats, true);
        xmlhttp.send();
    }
    
    function VulGegevensIn() {
        for (gang in Gerechten) {
            Gangen.options[Gangen.options.length] = new Option(gang, gang);
        }
        Wijzigen();
    }
    
    
    function Wijzigen() {
        GekozenGang = Gangen[Gangen.selectedIndex].text;
        if (Array.isArray(Gerechten[GekozenGang])) {
            MaakLijstLeeg();
            for (var teller = 0; teller < Gerechten[GekozenGang].length; teller++) {
                var optie = document.createElement('option');
                optie.value = Gerechten[GekozenGang][teller].Naam;
                optie.innerHTML = Gerechten[GekozenGang][teller].Naam;
                Menus.appendChild(optie);
            }
            Menus.selectedIndex = [0];
        }
        Updaten();
    }
    
    function MaakLijstLeeg() {
        for (var i = 0; i < Gangen.options.length; i++) {
            Menus.options.remove(i);
        }
    }
    
    function Updaten() {
        Naam.innerHTML = (Gerechten[GekozenGang][Menus.selectedIndex].Naam);
        Prijs.innerHTML = (Gerechten[GekozenGang][Menus.selectedIndex].Prijs + " Euro");
        Beschrijving.innerHTML = (Gerechten[GekozenGang][Menus.selectedIndex].Beschrijving);
        Foto.src = ("Afbeeldingen/" + (Gerechten[GekozenGang][Menus.selectedIndex].Foto));
    }
    
    
    function Bestel() {
        AantalPersonen = Aantal.value.replace(/\s/g, '');
    
        if ((isNaN(AantalPersonen)) || (AantalPersonen == "") || (AantalPersonen < 0)) {
            alert("Gelieve enkel cijfers in te voeren.");
        }
        else {
            InBestelling.push(Gerechten[GekozenGang][Menus.selectedIndex]);
            AantalPers.push(AantalPersonen);
            SoortGang.push(Gangen[Gangen.selectedIndex].text);
            UpdateBestelling();
    
    
            if (AantalPersonen == 0) {
                InBestelling.splice(Gerechten[GekozenGang][Menus.selectedIndex]);
                AantalPers.splice(AantalPersonen);
                SoortGang.splice(Gangen[Gangen.selectedIndex].text);
    
                UpdateBestelling();
            }
        }
    }
    
    
    function UpdateBestelling() {
        var Bestelling = document.getElementById('Bestelling');
        if (Bestelling != null) {
    
            Bestelling.parentElement.removeChild(Bestelling);
    
        }
    
    
        var NieuweBestelling = document.createElement('div');
        NieuweBestelling.id = 'Bestelling';
        NieuweBestelling.classList = 'Keuzes';
        NieuweBestelling.innerHTML = "<h1>Uw bestelling</h1>";
        Main.appendChild(NieuweBestelling);
    
        for (var i = 0; i < InBestelling.length; i++) {
            var Overzicht = document.createElement('p');
            Overzicht.id = i;
            Overzicht.classList = 'UwBestelling';
            Overzicht.innerHTML = (SoortGang[i]) + " <br/>" + InBestelling[i].Naam + " prijs : " +
                InBestelling[i].Prijs + " aantal besteld: " + AantalPers[i];
            document.getElementById('Bestelling').appendChild(Overzicht);
    
    
        }
        BerekenTotaalPrijs();
    
        var Totaal = document.createElement('div');
        Totaal.id = "TotaalPrijs";
        Totaal.classList = "Totaal";
        Totaal.innerHTML = "Totaalprijs : " + Afrekenen;
        document.getElementById('Bestelling').appendChild(Totaal);
    
        Aantal.value = "";
        Aantal.focus();
    
    }
    
    
    function BerekenTotaalPrijs() {
        Afrekenen = 0;
        for (var i = 0; i < InBestelling.length; i++) {
            Afrekenen += InBestelling[i].Prijs * AantalPers[i];
            Afrekenen = Math.round(Afrekenen * 100) / 100;
            
        }
        return Afrekenen;
    }
    JSON FILE
    Code:
    {
        "Voorgerechten": [
          {
            "Naam": "Sprinkhaan",
            "Beschrijving": "Krokante sprinkhaan op een bedje van kakkerlak",
            "Prijs": 5.99,
            "Foto": "Foto1.jpg"
          },
          {
            "Naam": "Tandoori Burger",
            "Beschrijving": "Burger op basis van Tandoori, een snelle hap als hongerstillertje",
            "Prijs": 4.99,
            "Foto": "Foto3.jpg"
          },
          {
            "Naam": "Cupcake",
            "Beschrijving": "Eetbare Cupcake, met wormpjes",
            "Prijs": 2.99,
            "Foto": "Foto9.jpg"
          }
        ],
        "Hoofdgerechten": [
          {
            "Naam": "Sushi",
            "Beschrijving": "Speciale sushi met een summum aan krakertjes",
            "Prijs": 7.99,
            "Foto": "Foto8.jpg"
          },
          {
            "Naam": "Insect Burger",
            "Beschrijving": "Een burger met lekkers en Pont-Neuf frietjes",
            "Prijs": 4.99,
            "Foto": "Foto5.jpg"
          },
          {
            "Naam": "Salade",
            "Beschrijving": "Salade op basis van zelfgevonden items",
            "Prijs": 1.99,
            "Foto": "Foto10.jpg"
          }
        ],
          "Desserts":
          [
            {
              "Naam": "Lolly",
              "Beschrijving": "Een lolly met inhoud een vleugje nostalgie",
              "Prijs": 2.99,
              "Foto": "Foto6.jpg"
            },
            {
              "Naam": "IJsje",
              "Beschrijving": "Lekker ijs met licht glimmende worms on the side",
              "Prijs": 2.99,
              "Foto": "Foto7.jpg"
            }
          ]
      }

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,769
    Error message and the line identified that is giving the error and the associated HTML for that section of code is also helpful.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  3. #3
    Join Date
    Jan 2018
    Posts
    11
    I get this error:
    xml parse error incorrectly formed gerechten.json line 1,1

    Thanks.

  4. #4
    Join Date
    Jan 2018
    Posts
    11
    HTML Code:
    !DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Resto Krokant</title>
    <meta charset="utf-8" />
    <style type="text/css" rel="stylesheet">
    body {
    background-color: lightgreen;
    }

    .detailfig {
    height: 180px;
    border: solid 2px;
    }

    h1 {
    text-align: center;
    color: green
    }

    .prijs {
    font-style: italic;
    font-weight: bold;
    font-family: sans-serif;
    color: red;
    }

    .naam {
    font-weight: bold;
    color: orange;
    font-family: sans-serif;
    }

    .bestel {
    border: solid 1px #638a00;
    border-radius: 3px;


    box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.4);
    font-size: 20px;
    color: #ffffff;
    padding: 1px 17px;
    background: #96c300;
    }

    .details {

    border: solid 5px green;
    background-color: #f1f1c1;
    margin-top: 20px;
    margin-left: auto;
    margin-right: auto;
    padding: 10px;
    width: 700px;
    height: 250px;

    }

    .Keuzes {
    border: solid 5px green;
    background-color: #f1f1c1;
    margin-top: 20px;
    margin-left: auto;
    margin-right: auto;
    padding: 10px;
    width: 700px;
    height: 250px;
    text-align: center;

    }

    .DetailTabel {
    width: 100%;
    height: 80%;

    }

    .hoofd {
    width: 200px;
    }
    .UwBestelling {
    margin: 1% 1% 1% 1%;
    padding-left: 2%;
    width: 94%;
    background-color: #f1f1c1;
    border: dashed green 3px;
    }
    .Totaal {
    border: solid red 3px;
    }
    </style>
    </head>

    <body>
    <h1> Resto 'Het Krokantje'</h1>
    <main id="main">
    <div id="divDetails" class="details">
    <table class="DetailTabel">
    <tr>
    <td width="50%">
    <img id="afbGerechje" class="detailfig" src="Afbeeldingen/Eetbare_Insecten.jpg" />
    <br/>
    <span class="naam" id="fotoTekst">Eetmogelijkheden</span>
    </td>
    <td>
    <b>
    <u> Naam :</u>
    </b>
    <p class="naam" id="naamGerecht">Intro</p>
    <b>
    <u>Prijs :</u>
    </b>
    <p class="prijs" id="prijsGerecht">0.00</p>
    <b>
    <u> Beschrijving : </u>
    </b>
    <p class="tekst" id="beschrijvingGerecht">Welkom</p>
    </td>
    </tr>
    </table>
    </div>

    <div class="Keuzes">
    <b>Gang : </b>
    <br/>
    <select class="hoofd" id="hoofd"></select>
    <p></p>
    <b>Keuze :</b>
    <br/>
    <select class="hoofd" id="sub" size="5"></select>
    <p></p>
    <b>Aantal personen : </b>
    <input type="text" class="aantal" size="3" id="aantal" value=0>
    <p></p>
    <input type="button" class="bestel" id="knop" value="Bestel">
    </div>
    <!-- Link naar de script-file -->
    <!-- <script type="text/javascript" src="JavaScript_Krokant/JS_Krokantje.js"></script> -->

    </main>
    <script type="text/javascript" src="JavaScript_Krokant/Krokantje.js"></script>
    </body>

    </html>

  5. #5
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,769
    When I said error, I also meant the actual line number and you only needed to post the code around that line number not the whole lot of code

    The reason I ask this is because that error is IMHO saying that theirs an error in parsing the JSON data, using JSONlint to validate, it says your JSON is A OK which leads me to believe that your error may lay elsewhere, so its a process of figuring out what is wrong at that point in the code.

    So please try to give the actual line number reported in the browsers console, what line number and what is that line of code.

    example
    JavaScript:
    Code:
    var myVariable = document.getElementByNoIdea("cheese");
    and HTML:
    HTML Code:
    <div id="cheese">... some content</div>
    Errors:
    Code:
    Uncaught Exception: your code is hurting me! at line 43:html
    and so on. Sometimes during writing up an error is spotted and you resolve the matter by seeing a mistake you made, others may know instantly what the problem is and it helps to have all the relevant information at hand.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  6. #6
    Join Date
    Jan 2018
    Posts
    11
    I get this error:
    xml parse error incorrectly formed gerechten.json line 1,1

    the error is on line 1,1 {

    {
    "Voorgerechten": [
    {
    "Naam": "Sprinkhaan",
    "Beschrijving": "Krokante sprinkhaan op een bedje van kakkerlak",
    "Prijs": 5.99,
    "Foto": "Foto1.jpg"
    },

  7. #7
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,769
    BUT if you go to https://jsonlint.com/ and test it, your code for the file is reported as valid
    Code:
    Results
    Valid JSON
    So it is helpful to know what other errors there are as that erro reference is not at all helpful in any meaning, generally literals like that are line 1 like anonymous functions (some call lambda's) are also prone to mis reporting the error.

    So either this file you posted is only a portion of a much larger file or as I suspect, the problem is within the parsing phase and getting to the bottom of that is the next step.

    What I suggest is that you edit the JSON file and put up a JSON file with a single entity in it, then add the next entity until you have filled the file and if you still get an error, then IDK what to suggest as there is clearly something that is interfering with the JSON process, I am assuming that the JSON file is not being rendered but a static device?

    I have to be quick as I am off out in 20 minutes, got a 50 mile drive ahead in this wind..! Got blown from one lane of the highway in to another whilst on the motorway yesterday...

    I will catch up later on if I miss your reply.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  8. #8
    Join Date
    Jan 2018
    Posts
    11
    I get the null in the next method:
    function BerekenTotaalPrijs() {
    Afrekenen = 0;
    for (var i = 0; i < InBestelling.length; i++) {
    Afrekenen += InBestelling[i].Prijs * AantalPers[i];
    Afrekenen = Math.round(Afrekenen * 100) / 100;

    }
    return Afrekenen;

  9. #9
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,769
    Have you tried to echo the output to the console .log?

    Code:
    function BerekenTotaalPrijs() {
    Afrekenen = 0;
    for (var i = 0; i < InBestelling.length; i++) {
    Afrekenen += InBestelling[i].Prijs * AantalPers[i];
    Afrekenen = Math.round(Afrekenen * 100) / 100;
    console.log("No. %s = %s",i, Afrekenen);
    }
    return Afrekenen;
    }
    and see what is wrong? If you are getting a NULL as a return, it often means that you have a data element that is NULL.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  10. #10
    Join Date
    Jan 2018
    Posts
    11
    I have tried the cosole.log, but my calculation total price is correct.

    I think i have to place a parseFloat on my js file. But i don't find where.

  11. #11
    Join Date
    Dec 2012
    Posts
    1,609
    I have created a test page using the code you posted and everything works fine. If your page is online then please post the URL so that one can analyze the error.

  12. #12
    Join Date
    Jan 2018
    Posts
    11
    My page is not online. But i have another question. When i load my page in firefox it works but when i load my page in google chrome i get an error.
    Failed to load file:///C:/Informatica%20HBO5/2017%20-%202018/A06%20Programmeren%202/Krokantje_Basismat/JSON/Gerechten.json: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

    What can i do to work it also in Chrome.

  13. #13
    Join Date
    Dec 2012
    Posts
    1,609
    In order to fix this you need to run your page on a webserver, either by uploading it to your webspace or by installing a local webserver like XAMPP.

  14. #14
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,769
    As Sempervivum has pointed out, upload it to a server, if you have none then sign up for a freebie web hosting site to test your code.

    http://lmgtfy.com/?q=free+web+hosting
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  15. #15
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,769
    Quote Originally Posted by Olivier1977 View Post
    I have tried the cosole.log, but my calculation total price is correct.

    I think i have to place a parseFloat on my js file. But i don't find where.
    If the console is getting output that you are expecting, then the problem is in the dealings after the function returns the result which is anything from an array or object of things to a string, number or boolean.

    If you read up about the JSON format, you will soon realize that you can "parseFloat" the file as the file is data, a string not a thing (yet) thats what parse in JSON does, turns it from a string to a thing and don't confuse parseInt, parseFloat as having anything to do with the JSON.parse() at all.

    So please do as Sempervivum suggests then report back what the errors are in your browsers console log, if you have errors, note what lines they are on and find them in the editor. If you have created a compound statement (or as some say stackked functions) whic hs where you do something like var myresult = aFunctionCall( doingSomeOtherFunction( guessWhat( variableToMessWith ) ) ); then you really need to break the statement down in to its individual parts like
    Code:
    var myresult = guessWhat( variableToMessWith );
    myresult = doingSomeOtherFunction( myresult );
    myresult = aFunctionCall( myresult );
    then see where the error occurs, its a pain but part of the job.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center

"

"

X vBulletin 4.2.2 Debug Information

  • Page Generation 0.52287 seconds
  • Memory Usage 3,049KB
  • Queries Executed 16 (?)
More Information
Template Usage (35):
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (7)bbcode_code
  • (1)bbcode_html
  • (3)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (15)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (15)postbit
  • (15)postbit_onlinestatus
  • (15)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (73):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates