Wikipedia project: officially, i hate it...... help me[[[[[mostly SOLVED]]]]]]

okay, so after trying to write my own, and trying to observe others’ code, and trying to re form it, the way i want it to happen… after searching the wiki API and tons of other resources for this information… i cant get it to do what i want… im in tears… i can properly call the information… but how do i make it display it??? anytime i try it gives me errors…

We can help you much better if you show us your code. Either a link a pen or cut and paste of the code.

https://codepen.io/EvonyJade/pen/zWxveR

this is what it is at the moment… but ive been adding and taking and im actualy at a point im getting frustrated… so idk even if im going the right direction anymore

You’re in the right direction for sure, but you got several critical bugs preventing you from finishing.

First error, your API url. You are adding unnecessary parameters at the end. Remove the callback and other parts and just leave it at this:

https://en.wikipedia.org/w/api.php?action=opensearch&search=mcdonalds&format=json

Second problem: your button is a submit. By default, submit buttons in the browser reload the page once they are pressed. This is because the point of using a submit button is to collect data from a form and submit it to a server. You aren't submitting any data to the server from the form, so there is no need to use a submit button, and no need to have the page reload. To fix this, you can add `e.preventDefault()` in your event handler on the `submit` event, but the easier fix since you are just getting the click event is to just remove the submit part altogether since you aren't submitting anything:
<button id="search">search</button>
document.getElementById("search").addEventListener("click", getQueryData);

Third, you need to run some checks and simple debugging to see what or if you are getting any data. Add a console.log in your function here:

function formatSearchString() {
  var searchString = document.getElementById("searchBox").value;
  var words = searchString.split(" ");
  searchString = words.join("_");

  console.log(searchString);

  return searchString;
}

And guess what? Nothing is getting logged. This tells us that formatSearchString() isn’t getting called. So, we check the next function:

function getQueryData() {
  console.log('click worked')
  // ...snip...
}

And… nothing again. Our click handler isn’t working properly. Let’s investigate why. Here is your code:

function formatSearchString(){

var searchString = document.getElementById("searchBox").value;
var words = searchString.split(" ");
searchString = words.join("_");
return searchString;
}

function getQueryData() {

var stringToSearch = formatSearchString();
var wikiUrl = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + stringToSearch + "&format=json&callback=wikiCallbackFunction&origin=*";

$.ajax(wikiUrl, {
type:'GET',
dataType: "jsonp",
  data: {
    title: "",
    summary: "",
    link: wikiUrl,
  },
  success: function(data) {
  document.getElementById("results").innerHTML = data.title[0].value; 
    document.getElementById("results2").innerHTML = data.summary[0].value;
    
  document.getElementById("results3").innerHTML = data.link[0].value;
    
  }

})
  
  
 document.getElementById("submit").addEventListener("click", getQueryData);
document.getElementById("searchBox").addEventListener("keypress", function(e) {

if (e.which == 13) {

e.preventDefault();
getQueryData();

}

return false;

});}

I will be honest with you. Your code there looks like crap. You are wondering why you can’t find the issue? It’s because your code is a mess. Nothing is wrong with your logic, but your code is unorganized and messy. I’m not trying to be a jerk, but be real. I hate it when I see code like this. It makes me almost in tears. We format and indent our code for a purpose. I’m going to show you what your code should look like, and it’s as simple as pressing the tidy button in your codepen editor:

Your code will look all nice and organized like this (with my minor changes regarding the submit point above):

function formatSearchString() {
  var searchString = document.getElementById("searchBox").value;
  var words = searchString.split(" ");
  searchString = words.join("_");
  console.log(searchString);
  return searchString;
}

function getQueryData() {
  console.log('click worked')
  var stringToSearch = formatSearchString();
  var wikiUrl =
    "https://en.wikipedia.org/w/api.php?action=opensearch&search=" +
    stringToSearch +
    "&format=json";

  $.ajax(wikiUrl, {
    type: "GET",
    dataType: "jsonp",
    data: {
      title: "",
      summary: "",
      link: wikiUrl
    },
    success: function(data) {
      document.getElementById("results").innerHTML = data.title[0].value;
      document.getElementById("results2").innerHTML = data.summary[0].value;

      document.getElementById("results3").innerHTML = data.link[0].value;
    }
  });

  document.getElementById("search").addEventListener("click", getQueryData);
  
  document
    .getElementById("searchBox")
    .addEventListener("keypress", function(e) {
      if (e.which == 13) {
        e.preventDefault();
        getQueryData();
      }

      return false;
    });
}

Now I didn’t tell you that because I wanted to be nitpicky. As I said before, there is a reason we format and organize and indent our code. Let’s go back to our problem. Our click event handler isn’t being called. Now that our code is properly indented, let’s look and see where our click event handler is…

function getQueryData() {
  console.log('click worked')
  var stringToSearch = formatSearchString();
  var wikiUrl = "...snip...";

  $.ajax(wikiUrl,{snip});

  document.getElementById("search").addEventListener("click", getQueryData);
  
  document
    .getElementById("searchBox")
    .addEventListener("keypress", function(e) {
      if (e.which == 13) {
        e.preventDefault();
        getQueryData();
      }

      return false;
    });
}

The error here should become apparent almost immediatly, and you would have never noticed it if you hadn’t formatted your code properly. You have your click event handlers inside your function. This ain’t gonna work. Your function won’t be called until the click event, and your click event never registers because it’s inside the function. Circular logic. To fix, just put the click event handler in the global scope. Oh, and after you move it, hit tidy again so the indentation fixes itself.


Number Five. After making above changes, recheck the console, and you should see the logs and an error as well:
Uncaught TypeError: Cannot read property '0' of undefined
    at Object.success (pen.js:26)
    at u (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at k (jquery.min.js:2)
    at HTMLScriptElement.n (jquery.min.js:2)
    at HTMLScriptElement.dispatch (jquery.min.js:2)
    at HTMLScriptElement.y.handle (jquery.min.js:2)

Alright, so something in our data is undefined. Let’s log the data so we can actually see what we are getting:

success: function(data) {
  console.log(data)
  // ...snip...
}

And when I do a search, I get an array in the console I can look at. Another way to look at the data is to open it up in your browser. I’ll search for something I know will have a lot of articles:

https://en.wikipedia.org/w/api.php?action=opensearch&search=trump&format=json

In your browser, you might get a jumbled mess of text. You can install a browser plugin to format this for you, and should see your data will look like this:

[
  "trump",
  [
    "Trump",
    "Trump–Russia dossier",
    "Trump Tower",
    "Trumpet",
    "Trump International Hotel and Tower (Chicago)",
    "Truthiness",
    "Trump University",
    "Trump campaign–Russian meetings",
    "Trumpeter swan",
    "Trump family"
  ],
  [
    "Trump most commonly refers to:",
    "The Trump–Russia dossier, also known as the Steele dossier, is a private intelligence dossier of 17 memos that were consecutively written from June to December 2016 by Christopher Steele, a former British intelligence (MI6) officer.",
    "Trump Tower is a 58-story, 664-foot-high (202 m) mixed-use skyscraper at 721–725 Fifth Avenue between 56th and 57th Streets in Midtown Manhattan, New York City.",
    "A trumpet is a brass instrument commonly used in classical and jazz ensembles. The trumpet group contains the instruments with the highest register in the brass family.",
    "The Trump International Hotel and Tower, also known as Trump Tower Chicago and Trump Tower, is a skyscraper condo-hotel in downtown Chicago, Illinois.",
    "Truthiness is the belief or assertion that a particular statement is true based on the intuition or perceptions of some individual or individuals, without regard to evidence, logic, intellectual examination, or facts.",
    "Trump University (also known as the Trump Wealth Institute and Trump Entrepreneur Initiative LLC) was an American for-profit education company that ran a real estate training program from 2005 until 2010. It was owned and operated by The Trump Organization.",
    "Members of the 2016 Trump campaign had several meetings with individuals who were perceived to have Russian connections.",
    "The trumpeter swan (Cygnus buccinator) is a species of swan found in North America. The heaviest living bird native to North America, it is also the largest extant species of waterfowl with a wingspan that may exceed 10 ft (3.0 m).",
    "The Trump family (German: [ˈtʁʊmp]; Palatine German: [ˈdrʊmpʰ]; American English: ) is a German and German-American family, descended from Johannes Trump, a native of the village of Kallstadt in then Electoral Palatinate, Holy Roman Empire, today in modern Germany."
  ],
  [
    "https://en.wikipedia.org/wiki/Trump",
    "https://en.wikipedia.org/wiki/Trump%E2%80%93Russia_dossier",
    "https://en.wikipedia.org/wiki/Trump_Tower",
    "https://en.wikipedia.org/wiki/Trumpet",
    "https://en.wikipedia.org/wiki/Trump_International_Hotel_and_Tower_(Chicago)",
    "https://en.wikipedia.org/wiki/Truthiness",
    "https://en.wikipedia.org/wiki/Trump_University",
    "https://en.wikipedia.org/wiki/Trump_campaign%E2%80%93Russian_meetings",
    "https://en.wikipedia.org/wiki/Trumpeter_swan",
    "https://en.wikipedia.org/wiki/Trump_family"
  ]
]

I don’t see any title or anything in the data that would make these work:

document.getElementById("results").innerHTML = data.title[0].value;
document.getElementById("results2").innerHTML = data.summary[0].value;

Let me give you a better URL to use, because I think you’ve accomplished the main point of the project. Try using this url:

https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&utf8=1&srsearch=trump

I think this is the one you were trying to model your data after. You should then modify your url and you can remove the data object as it is redundant. Here is what my call looks like:

$.ajax(wikiUrl, {
    type: "GET",
    dataType: "jsonp",
    success: function(data) {
      console.log(data)

      document.getElementById("results").innerHTML = data.title[0].value;
      document.getElementById("results2").innerHTML = data.summary[0].value;
      document.getElementById("results3").innerHTML = data.link[0].value;
    }
  });

Whew. Finally, we are getting the data we need, now it is just an exercise in pulling the correct values off of the data. I'll let you work this one out yourself. It shouldn't be too difficult now that you are getting the data you need and know how to inspect it. If you need a reference, I'll paste the code I used a long time ago in my project, but I strongly urge you to try and figure it out yourself by opening the link in a new tab and the console and figuring out where all the titles and snippets are in your data object.
var searchItem = $('input[type=text]').val();
    $.getJSON("https://en.wikipedia.org/w/api.php?action=query&format=json&limit=15&list=search&utf8=1&srsearch=" + searchItem + "&callback=?", function (json) {
      var pages = json.query.search.length;
      for (var index = 0; index < pages; index++) {
        var pageTitle = json.query.search[index].title;
        var pageSnippet = json.query.search[index].snippet + '...';
        $('#results').append('<div class="result"><div class="title">' + pageTitle + '</div><div class="snippet">' + pageSnippet + '</div></div>');
      }
    });

Good luck, hope this helped!
2 Likes

No no. I know its a mess lol i was working on it last night and i started just trying to throw my concepts together without actually taking my time to clean it up… Its reassuring that im going in the right direction… I think through it all, at one point i got my way to picking the data, but somewhere i undid something… But yes this deffinitely helps… Tonight i will be able to take a better look into your advise and apply it thank you

Cool.

But relax. These things are difficult. If they weren’t, then these jobs would pay minimum wage. Everyone struggles with these.

1 Like

If this Helps, this is the API i used:

 var api =
    "https://en.wikipedia.org/w/api.php?action=opensearch&search=" +
    search +
    "y&format=json&origin=*";

and to call it:

$.ajax({
    type: "GET",
    url: api,
    async: false,
    success: function(data) {
// This is where you can sort through the object/ search results and do whatever you want displaying them.
});

This project was also highly confusing to me, as the API’s i saw people used never worked and constantly changed.

To find a working API for me took make a hour of searching.

I tried to do that but idk ill try again…

Haha right. I think i was just having a moment…

I categorized your post, and edited the title to include “project:”. Your title was giving the impression that you hated Wikipedia. Clarity is important and wrong impressions aren’t good. I’m pretty sure we all like Wikipedia. I hope so anyway.

1 Like

ok isaac, so ive gone through this, and while alot of it does help, i am still getting a bunch of errors like when you said “data is undefined” im not quite sure what i can be doing wrong, if your blatently telling me how to fix it… i feel like an idiot. lmao… it wont do the thing. hahahaha anyways, i cant get it to log my data in my console… i can use the link to find it in my browser just fine, as that chunk of messy strings…but never in my console… am i doing something wrong? i know in my weather app i actually had to fix things in my browser i guess i worry thats an issue again… im going to try to redo it once more… but if im stumped ill repost it here and see what im doing wrong this time… :frowning:

what does violation click handler mean?

okayseems im stuck on applying the data to the page… ive tested it step by step, and got the arrays to show up in my console log… but now im stuck

Ok so this is your data. It is an array of 4 items.

So to reference an array elements use bracket notation.

data[0] will equal “Kelly”
data[1] will equal an array of 10 article titles and so on.

ok i thought that might be where im headed with that… thank you

okay so, ive got some kind of something going now… but im pretty sure its more meticulous than it should be, but im okay with that, im just worried will it affect the run time of it all processing wise? also… i can get something to display on the page… for about 2 ms… then its gone… is there something i need to be doing to hold it there?

I looked at you codepen quickly… you are getting a console error because you are missing “event” on your first line:
Add event inside the brackets of your function searchStuff

$("#search").on("click", function searchStuff(event) {

Hey thans. I actually figured it out… Igot it all working and finished it in another pen… Im now working on twitch tv

1 Like