I'm fairly new to both jQuery and Ajax, and have faced a problem when trying to use WordPress oEmbed with the help of Ajax.
This is what I have in functions.php at the moment:
function ajax_magic()
{
wp_localize_script( 'function', 'display_videos', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
function get_video_link()
{
echo wp_oembed_get($_POST['link']);
die();
}
add_action('template_redirect', 'ajax_magic');
add_action('wp_ajax_get_video_link', 'get_video_link');
My jQuery looks like this:
function display_video(input,output)
{
var link = document.getElementById(input).value;
jQuery.ajax({
url: display_videos.ajaxurl,
type: 'POST',
data:{
action: 'get_video_link', // this is the function in your functions.php that will be triggered
url: link
},
success: function(data){
//Do something with the result from server
$('#'+output).html(data);
}
});
}
The input option is the url to the video, the output option contains the ID of the div where the result of the ajax function should be echoed.
The url of the video is fetched from a form field when clicking a preview button (not the submit button).
Right now, nothing happens, but I can't see any errors in the Javascript Console.
As I said, I'm fairly new to this, so maybe I have missed something very basic, or something like that.
By the way, this is how I implement the javascript functions file (general.js) inside functions.php. This works, but maybe I need to do it another way to make Ajax work?
function lets_add_scripts() {
wp_register_script('general', get_bloginfo('template_directory') . '/js/general.js', array('jquery'),'', false);
wp_enqueue_script('general');
}
add_action( 'wp_enqueue_scripts', 'lets_add_scripts' );
Thanks for any help you can give me, it's greatly appreciated!
// Jens.
You're trying to localize a non-existent script with the handle
function
. From the rest of your code it is clear you're targetinggeneral
. Not sure why you hook intotemplate_redirect
to localize, just add the localization part after the enqueue: