2

Basically what I am trying to achieve with this section of code is to search with a term on twitter, and then see if the second term is included in any of the search results. tally those up and graph them with the Google charts api. it seems indexOf, is not working because when i declare term and term2 to be both "test" It still only adds to notcontains.

$.ajax({
    url: 'http://search.twitter.com/search.json?q=' + term2 + '&lang=en&callback=?',
    dataType: "json",
    async: false,
    success: function(data) {
        var data = data.results;
        var addhtml = "<ul>";
        for (var i = 0; i < data.length; i++) {
            addhtml += "<li><a href='http://twitter.com/" + data[i].from_user + "'>@" + data[i].from_user + "</a>: " + data[i].text + "</li>";
            compare = JSON.stringify(data[i].from_user);
            if (compare.indexOf(term) >= 0) contains += 1;
            else notcontains += 1;
        }
        addhtml += "</ul>"
        html += addhtml;
        drawChart()
        $('.content').html(html);
        $('.counts').html(contains + " " + notcontains);
    }
});
Esailija
  • 138,174
  • 23
  • 272
  • 326
Chris
  • 35
  • 1
  • 6
  • Check the 'compare' variable, i don't know what u get back from twitter but it looks to me you are setting it with the wong value to be checked against the term variable. – Shikyo Nov 03 '12 at 20:20
  • 1
    If the return dataType is in the form of `'json'` .. `JSON.stringify` is redundant .. Also how does your json string look like – Sushanth -- Nov 03 '12 at 20:42
  • The code is correct. When searching for 'test' there is no resulting tweet that also has test in the username. Are you sure you are checking the correct property ´from_user´ ? What are you trying to do? – Jesper Palm Nov 03 '12 at 20:47
  • Oh wow, Thank you for pointing that out, I cant believe i missed that. It works now. Thank you. I was literally searching for a solution for hours.... – Chris Nov 03 '12 at 21:01
  • @Chris: FWIW, "hours" is not a particularly long duration of time to solve a programming problem. Patience is a virtue! – Lightness Races in Orbit Nov 03 '12 at 21:08

2 Answers2

0

The problem was that I was searching the username for the second term and not the text.

compare = data[i].from_user; 

should be

compare = data[i].text;
Chris
  • 35
  • 1
  • 6
-3

indexOf is used for finding the index of a value within an object or string...for testing if a property exists use hasOwnProperty as shown in this SO question

Community
  • 1
  • 1
Pastor Bones
  • 7,183
  • 3
  • 36
  • 56
  • I changed that if statement to if(compare.hasOwnProperty(term2)) and it still didn't work. I was browsing around and found (http://stackoverflow.com/questions/1789945/javascript-string-contains) so it seems like using index of is valid for searching for a string within a string ? – Chris Nov 03 '12 at 20:21
  • 3
    He is using indexOf for searching strings so the usage is valid. – Shikyo Nov 03 '12 at 20:36