Accessing an API with jQuery and AJAX

There are a few things going on with your functions.php file that may be the issue.

  1. You should be using wp_enqueue_scripts action to enqueue your script.
  2. The first parameter of wp_localize_script() should match the id of the file you’ve enqueued.
  3. You also need to add a no_priv version for your Ajax call if it needs to work for non-logged in users. Have a read here for more details.

This is NOT a complete answer but you’ll need to get the WordPress portion fixed up before debugging the rest.

Hope this helps!

require_once( get_template_directory() . '/inc/init.php' );

function my_init() {
    if (!is_admin()) {

        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', false, '1.3.2', true);
        wp_enqueue_script('jquery');


        // load a JS file from my theme: js/theme.js
        wp_enqueue_script('instant_search', get_bloginfo('template_url') . '/js/instant_search.js', array('jquery'), '1.0', true);

        //id must match the enqueued script id
        wp_localize_script( 'instant_search', 'my_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

    }
}

//use this action instead
add_action( 'wp_enqueue_scripts', 'my_init');



$dirName = dirname(__FILE__);
$baseName = basename(realpath($dirName));
require_once ("$dirName/twitter_search.php");

//this will work for logged in users only
add_action("wp_ajax_get_my_option", "get_my_option");

//this will work for non-logged in peeps
add_action("wp_ajax_no_priv_get_my_option", "get_my_option");

EDIT:

Make sure your script is being enqueued by putting an alert in document.ready(). Also, if you’re planning to use $ instead of jQuery inside the function, you should pass $ to it.

jQuery.(document).ready(function($){
    alert('loaded all the things');
    $('.selector').html('works only if $ is passed to the function');
});

You have a lot of moving parts and it’s impossible to tell whats not working without going at it step by step. Try the following in order.

  1. Confirm your script being enqueued properly – need this for wp_localize_script
  2. Confirm the vars are being localized – need this for ajax_url ( hint: check the source of the page)
  3. Confirm ajax is calling and correctly returning a response – need this to get the data
  4. Confirm that whatever your ajax method is doing actually works and does what you want. It’s accesssing Twitter – does it need to be authenticated. I’m pretty sure they deprecated v1 of the api …

Going into more detail would be basically doing it for you so I’ll leave the details to you 🙂

Best of luck!