1

I am having trouble with working with AJAX + JSON, every time I try to dynamically write something on my web page, other functionalities just stop working...

Here is my JS code:

window.onload = function(){
    $.ajax({
        url: "data/faq.json",
        method: "POST",
        dataType: "json",
        success: function(faq){
            ispisFAQ(faq);
        },
        error: function(error){
            console.error(error);
        }
    });
    
    
    function ispisFAQ(faq){
        let ispis = '<div class="row faqRow">';

        faq.forEach(element => {
            ispis += `
            <button class="${element.class}"> ${element.question} </button>
            <div class="content">
                <p>
                    ${element.answer}
                </p>
            </div>`;
        });
        ispis += '</div>';
        document.getElementById("faqContainer").innerHTML = ispis;
    }
  }

And here is JSON file :

[
    {
        "class": "collapsableQuestion",
        "question": "1. Do you have a store?",
        "answer": "Yes, I do! Currently I have one store on 2424 George Street in Toronto. You can see all the pieces and more there in person!"
    },
    {
        "class": "collapsableQuestion",
        "question": "2. Do you ship internationally?",
        "answer": "Unfortunately, no. I only ship to Canada, but I'm working on expanding!"
    },
    {
        "class": "collapsableQuestion", 
        "question": "3. What is your return policy?",
        "answer": "Your complete satisfaction is my number one concern.If you are not completely satisfied with your selection, you can return it within 30 days."
    },
    {
        "class": "collapsableQuestion",
        "question": "4. What is your jewelry made of?",
        "answer": "Quality is very important to me. So I make sure that every piece is made of Gold plated .925 sterling silver. I guarantee that it will last you a long time, with no damage."
    },
    {
        "class": "collapsableQuestion",
        "question": "5. Do you clean/repair jewelry?",
        "answer": "If it's one of my pieces, sure! Just contact me with details." 
    },
    {
        "class": "collapsableQuestion",
        "question": "6. Do you make any custom jewerly?",
        "answer": "It's not something I do very often, but if you like the style of my jewerly, price and quality - contact me, and I will see what I can do."
    }
]

But when I try to run code below, to toggle some content it won't work...

var tog = document.getElementsByClassName("collapsableQuestion");

for (var i = 0; i < tog.length; i++) {
    tog[i].addEventListener("click", function () {
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.display === "block") {
            content.style.display = "none";
        } else {
            content.style.display = "block";
        }
    });
}

Please help me, when I run the same code without AJAX and JSON it works fine, what is the problem?

YosiFZ
  • 7,792
  • 21
  • 114
  • 221
  • 1
    One question - why are you running a POST request? don't you want to run a GET request to fetch the json file? – amyloula Mar 03 '19 at 12:31
  • Can you try to write code in Jquery way, for example instead of using window.onload and tog[i].addEventListener, you can use jquery $( document ).ready(function() and $.on('click', function(event) – Pakira Mar 03 '19 at 12:48
  • If I understand correctly, the issue that you are having is that not all of the collapsable questions are toggling correctly. If so, as you are using jQuery, the most straightforward way to ensure that all classes toggle correctly would be like so: `function toggleAll() { var tog = document.getElementsByClassName("collapsableQuestion"); for (var i = 0; i < tog.length; i++) { tog[i].addEventListener("click", function () { this.classList.toggle("active"); $(this).siblings().toggleClass( "active", false); }); } }` – amyloula Mar 03 '19 at 12:50
  • execute the toggleAll function like so: `$( document ).ready(function() { toggleAll(); });` – amyloula Mar 03 '19 at 12:52
  • Yes, my problem is that it won't toggle. But, when I run my code( shown above) without ajax it works just fine... Why is ajax the problem? I have two JS files, "main.js" and "script.js" where "script.js" has javascript and jquery code in one(again, working totally fine when ajax isn't involved), and for "main.js" i wanted it to be just for ajax and functions I make for it. – Lenka Živković Mar 03 '19 at 13:10
  • @amyloula As far as I know, you can use POST and GET method, there are differences, but since this is a school project it doesn't matter which one I use. I am not sharing any sensitive or important data. – Lenka Živković Mar 03 '19 at 13:19
  • @LenkaŽivković even if it is just a school project, you should use the correct HTTP method for the correct request. If you are getting data then you should use a GET request and if you are creating data you should use POST, if you are updating data you should use PUT. https://www.restapitutorial.com/lessons/httpmethods.html – amyloula Mar 03 '19 at 13:22

1 Answers1

-1

It seems to me you are forgetting to parse the json: When you receive the response to your ajax request, it's considered as text. Here's what you should do:

window.onload = function(){
$.ajax({
    url: "data/faq.json",
    method: "POST",
    dataType: "json",
    success: function(content){
        var data = JSON.parse(content)
        ispisFAQ(data);
    },
    error: function(error){
        console.error(error);
    }
});

(note the JSON.parse() call) This function converts the text you received to a javascript object you can interact with.

Cheers!

Edit: By the way, you should check out the fetch API. It is often easier to use, and allows cleaner code

bastien girschig
  • 663
  • 6
  • 26
  • 1
    No. jQuery ajax will parse an HTTP response as JSON if (a) `dataType` is "`auto"` and the `Content-Type` says it is JSON **or** (b) `dataType` is `"json"`. Also, if the problem was that the JSON wasn't being parsed then the problem would be that *the data doesn't show up* not that the toggle functionality didn't work. – Quentin Mar 03 '19 at 12:33
  • Oh, you're right... I'm actually not very used to jQuery and answered a bit too fast. sorry for that. – bastien girschig Mar 03 '19 at 12:38