Finished wiki viewer (JavaScript)

I know it’s not much to look at at the moment as I need to style it up. I was just curious though about how I wrote the output statement in JavaScript section. Was my solution for this project a bit bad?

This is not a valid HTML (you can’t have input inside button):

<button type='button' input type="submit" value='Submit' id="search" class="btn btn-info btn-md">Let's Search!</button>

You don’t need corseverywhere if you add origin: '*' in data:

      data: {
        action: "opensearch",
        format: "json",
        search: searchTerm,
        limit: 20,
        formatversion: 2,
        origin: '*',

You can use ES6 string templates to get rid of concatenation:

        for (let i = 0; i < a.length; i++) {
          output += `<div><p>${a[i]}<br>${b[i]}<br><a href="${c[i]}">${c[i]}</a></p></div>`;

Also if you search for gibberish like skfhjklsajfkljslkfjsk nothing happens.

Suggestion: Avoid mystery variables like these… give them descriptive names.

for(i=0; i<a.length; i++){
output+='<div>'+'<p>'+a[i]+'<br>'+b[i]+'<br>'+'<a href='+c[i]+'>'+c[i]+'</a></p></div>';

And also INDENT! It makes for readable code, and facilitates troubleshooting and getting a big picture overview of the code.

1 Like

In addition to what’s already been said (use distinct variable names and indenting properly), consider making a habit of adding an error handler to any api requests.

error: function (...) {  
     Alert('Not Good'); //Or a console.log statement

So I found that if I enter an invalid search term that the api will still send out an array of arrays but with length 0. Is it acceptable to use:

if (a.length===0) {
$(’#search-results’).html('Could not find anything with name: ’ +searchTerm);

in the success function and allow this to be my error handler in a sense then?

Or a variation of that anyways. I will rename my variables soon.

I might try to add some CSS Styling to it but for the most part you need to focus on valid syntax and that the functionality works.