0

As a proof of concept I'm trying to access an API using jQuery and AJAX and posting the results to a page. After following some online tutorials and doing my best to put it all together, I have the following:

functions.php:

//Fire Customizr
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);

        wp_localize_script( 'my_js_function', 'my_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

    }
}
add_action('template_redirect', 'my_init', 'init');

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

twitter_search.php:

$username = (empty($_REQUEST['username'])) ? FALSE : $_REQUEST['username'];

function get_my_option(){
    if($username !== FALSE){
        $url = 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name='.$username.'&count=5&include_entities=1&include_rts=1';
        // Get cURL resource
        $curl = curl_init();
        // Set some options
        curl_setopt_array($curl, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url
        ));
        // Send the request & save response to $resp
        $resp = curl_exec($curl);
        // Close request to clear up some resources
        curl_close($curl);
        if($resp){
            echo json_encode($resp);
        }
    }
}

instant_search.js

jQuery(document).ready(function(){
    var user = $('#username');
    var result = $('#resp');
    $('#grab').click(function(){
        if(user.val() !== ''){
            var config = {
                username: user.val()
            }

            function my_js_function(){
                jQuery.ajax({
                    url: my_ajax_script.ajaxurl,
                    dataType: "json",
                    data: ({action : 'get_my_option'}),
                    success: function(json){
                        for(x in json){
                            result.append(json[x].text);
                        }
                    }
                })
            };

        }
    }) 
});

Page post in WordPress:

<input type="text" id="username">
<button id="grab">Grab!</button>
<div id="resp">

</div>

I feel like I'm close to right, but a little in over my head when it comes to troubleshooting this. Any help would be greatly appreciated.

  • are there any errors being fired in your console? – Welcher Aug 25 '14 at 20:25
  • Not with this configuration. Nothing firing at all in fact. – whocares2021 Aug 25 '14 at 21:13
1

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!

  • Thanks for the help. I edited my functions.php to your specifications. Still not getting any results or log activity, but I'm sure it's a good start. – whocares2021 Aug 25 '14 at 22:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.