Testing reddit API

by Julian Garcia Castillo

HTML

<textarea id="text"></textarea>
<input id="get-comment" type="submit" value="Ask"/>
<p id="response"></p>
<hr>
<input id="get-posts"  type="submit" value="Get posts"/>
<h2></h2>
<h4></h4>

JavaScript

const subreddit1 = "doctors"
const sortType = "relevance"

const subreddit2 = "TwoSentenceHorror"
const sub2Sort = "hot" // top new hot

//SEARCH QUESTION AND COMMENTS FROM subreddit1
$('#get-comment').on('click', ()=> {
	const rawText = $('#text').val(),
			filteredText = rawText.replace(/\s/g, '+')


	var urlPosts = "https://www.reddit.com/r/"+subreddit1+"/search.json?q=title:"+filteredText+"&sort="+sortType+"&restrict_sr=on"


  $.getJSON(urlPosts, function(res) {
      // JSON result in `data` variable
      console.log(res)
      const bestMatch = res.data.children[0].data
      if (bestMatch) {
        console.log('similar title: ', bestMatch.title)

        var urlComments = "https://www.reddit.com/r/"+subreddit1+"/comments/"+bestMatch.id+".json"



        $.getJSON(urlComments, function(resC) {
            // JSON result in `data` variable
            console.log(resC)
            const bestComment = resC[1].data.children[0].data
            console.log("best comment:", bestComment.body)
            $('#response').html(bestComment.body) 
        });
      }
  });
})


// GET POSTS FROM subreddit2
$('#get-posts').on('click', ()=> {
	const rawText = $('#text').val(),
			filteredText = rawText.replace(/\s/g, '+')


	var urlPosts = "https://www.reddit.com/r/"+subreddit2+"/"+sub2Sort+".json"


  $.getJSON(urlPosts, function(res) {
      // JSON result in `data` variable
      console.log(res)
      const bestMatch = res.data.children[9].data
      if (bestMatch) {
        $('h2').html(bestMatch.title)
        $('h4').html(bestMatch.selftext)
      }
  });

})