Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Problem with simple if else statement when using Ajax

I don't know how to format the code for the questions so please help, so I can edit this question to make the code readable

I have a small and frustrating problem (albeit I think that it is small and stupid probably) and I have been on it for hours, trying different ways, switching variables around, and just doing stuff to see if it will work.

I have an XMLHttpRequest object and I have an API that returns spells and their effects. However in the generateSpellBody function the if() else() statement is not executing properly. I keep getting the result not a spell, no matter how I change the conditions, trying different methods, I tried indexOf() , json.parse etc. I keep getting the result of the else condition only inside the test.innerHTML. When I remove the else block, it works fine.

JavaScript:

const spells = 'https://{my-spells-api-and-auth-key}';
const spellBtn = document.querySelector('.spell-btn');
const spellTextBox = document.querySelector('#spell-text');
let test = document.querySelector('.test');

function getJson ( url, callback )  {
    const xhr = new XMLHttpRequest;
    xhr.open('GET', url);
    xhr.onload = () => {
        if (xhr.status === 200) {
            let data = JSON.parse(xhr.responseText);
            return callback(data);
        }
    };
    xhr.send();
}

function generateSpellBody (data) {
     data.map(dat => {
         if (dat.spell === spellTextBox.value) {
            console.log(dat.spell);
            test.innerHTML = dat.spell;
        } else {
            test.innerHTML = 'not a spell';
        }
    });
}

spellBtn.addEventListener( 'click', ( e ) => {
    e.preventDefault();
    getJson( spells, generateSpellBody );
} );

HTML:

 <form method='get'>
        <div class="form-group">
            <input type="text" class="form-control" id="spell-text" placeholder="Enter spell">
        </div>
        <button type="submit" class="spell-btn btn btn-default btn-light">Do spell</button>
    </form>

    <div class="test"></div>

Part of JSON data that I'm using:

[
    {
        "_id": "5b74ebd5fb6fc0739646754c",
        "spell": "Aberto",
        "type": "Charm",
        "effect": "opens objects"
    },
    {
        "_id": "5b74ecfa3228320021ab622b",
        "spell": "Accio",
        "type": "Charm",
        "effect": "Summons an object",
        "__v": 0
    },
    {
        "_id": "5b74ed2f3228320021ab622c",
        "spell": "Age Line",
        "type": "Enchantment",
        "effect": "Hides things from younger people",
        "__v": 0
    },
    {
        "_id": "5b74ed453228320021ab622d",
        "spell": "Aguamenti",
        "type": "Charm",
        "effect": "shoots water from wand",
        "__v": 0
    }
]

```
code
```

will look like

code

1 Answer

Steven Parker
Steven Parker
231,269 Points

The if/else is working fine, but it is done for every item in the list. Of course, the test will be true for at most just one item, and all the others will be handled by the "else". You can see the expected response only if the item entered is the last one tested (with this data, "Aguamenti").

The fix is to issue the failure response after the testing loop, and then only if nothing was found. This is similar to what was needed for the "student record search" exercise in the courses, if you recall that.

Thanks, which course was the student record search exercise?