Making jQuery $.ajax call to Twitter API 1.1 search

12,763

You cannot set request headers using AJAX calls with dataType JSONP.

See this question: Set Headers with jQuery.ajax and JSONP?

The best solution is to use a server-side proxy to do the search for you. I know you are looking for a client only solution, but with this restriction, and with no way around CORS, this is how it seems to be done today for the Twitter API.

Edit It may be possible using a proxy like Yahoo's YQL if you don't have access to one.

Share:
12,763
kscott
Author by

kscott

I program computers to do things for people.

Updated on June 04, 2022

Comments

  • kscott
    kscott almost 2 years

    Here is a very simple example of a call to Twitter's search API to get all tweets from a tag known to have tweets, #fml.

    I believe I am correctly using the application-only authentication as explained here: https://dev.twitter.com/docs/auth/application-only-auth (see Step 3 for example of a call)

    I am being asked for a solution that does not involve any server-side code so I am including the bearer code in the javascript, which isn't good to begin with, but....

    I would expect this code to work. Instead it produces the error '400 (Bad Request)'. Any ideas?

    $.ajax({
        url: "https://api.twitter.com/1.1/search/tweets.json",
        dataType: "jsonp",
        data: "q=%23fml",
        beforeSend:  function (xhr) { 
                 xhr.setRequestHeader ("Authorization", "Bearer XXmyBearerCodeXX"); 
                },
        success: function(json){ alert(json); }
    });
    

    EDIT 1 - Validated Twitter call

    Using hurl.eu I was able to get a successful response from the API with the above query and Authorization header, so I assume this means my Twitter call is correct, just not set up correctly within jQuery.ajax(), but I just don't see what is missing.