0

Hi I'm just trying to do some simple AJAX stuff by retrieving search results from Twitter. It is bringing back the objects but I can't seem to drill down to the object itself and get the info (such as text).

If I console.log(tweet), it lists all the objects, but the code below just says "undefined". I'm sure I'm missing something easy.

I've read loads of questions/answers on here but none seem to do it. I see many have used the .getJSON() method, but using .ajax() should be ok I would have thought?

    $.ajax({
        dataType: 'jsonp',
        url: 'http://search.twitter.com/search.json?callback=?&q=twitter&rpp=5',
        success: function (data) {
            $.each(data, function(i,tweet){
                console.log(tweet.text);
                //$('#twitter ul').append('<li><a href="' + item.text + '">' + item.from_user_id + '</a></li>');
            });
        }
    });

1 Answer 1

3

You have to use data.results

$.ajax({
    dataType: 'jsonp',
    url: 'http://search.twitter.com/search.json?callback=?&q=twitter&rpp=5',
    success: function (data) {
        $.each(data.results, function(i,tweet){
            alert(tweet.text);
            //$('#twitter ul').append('<li><a href="' + item.text + '">' + item.from_user_id + '</a></li>');
        });
    }
});

You can find a working sample here.

Updated:

I think you are new to javascript and json data format.

The data returned by the request http://search.twitter.com/search.json?callback=?&q=twitter&rpp=5 is in json format. The response for the request contains a key value pair. If you copy paste the request url in your browser you can see the result of the query.

It starts with {results: [....]}, it means that the json object contains an array of items which can be accessed used the key results.

Each item in the results array contains the following values

{
    "from_user_id_str":"",
    "profile_image_url":"",
    "created_at":"",
    "from_user":"",
    "id_str":"",
    "metadata":{"result_type":"recent"},
    "to_user_id":null,
    "text":"",
    "id":,
    "from_user_id": 0,
    "geo":null,
    "iso_language_code":"en",
    "to_user_id_str":null,
    "source":""
}

each of these key/values can be accessed with the the $.each(function(i, tweet){ .... }) using tweet.<key name>. Ex: tweet.from_user_id_str, tweet.text, tweet.source etc...

Sign up to request clarification or add additional context in comments.

1 Comment

Great! Thanks for that. I hadn't heard of data.results. Fogive the noob but are there any other data.X methods? When getting my delicious bookmarks (also json), I didn't need data.results. 'data' worked fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.