Using AJAX In WordPress Video Tutorial
Using AJAX in WordPress can be a tricky business. I’ve already explained how to use it in previous tutorials here on Return True, however after several requests I’ve finally made a video tutorial to give a more detailed explanation.
So it took a while thanks to my capture program just dieing on me, but I’ve finally managed to get this video done. As I said when I posted yesterday’s video I made this video before yesterday’s, but decided to keep it back as it needed a bit of editing & I didn’t have the time to do it then. That’s why this is a small video as I only managed to sort out my capture problems after I made this video.
There is a little jump in the video, I’ve no idea what caused it. I only noticed it while I was adding the zoom effects. It’s not in a important place, in fact I don’t think I was speaking when it happened so it should cause any problems. Anyway, I hope this video makes the whole process clearer.
This video is 560×350 and should be just good enough quality to full screen. I’ll try & make a better quality version at some point, but this should be ok for now.

Discussion: 21 Comments » add a comment
Thanks for the video tutorial!
It helped me a lot to understand and create an Ajaxed stuff for the admin panel , in a Custom Post Type that I use.
The important thing about using Ajax inside the admin panel, is to properly use the wp_enqueue_script() function, to have load it to the admin page.
Cool stuff.
No problem. Yes, using
wp_enqueue_script()is extremely important in most places within WordPress. It helps with AJAX inside the admin panel & when creating themes as it helps make sure scripts are loaded in the correct order.Hi, great tutorial.
How would I pass a variable from Javascript to the php function in function.php??
Thanks!
You would pass it along with the action & nonce. So it might look like this:
data = { action: 'wp_my_action', nonce: 'n497slk', var: 'another value' }The data should then be available in the
$_POSTglobal variable. Just remember to sanitize your data as you would any other user supplied data, just in case.Thanks a lot for your reply. It’s giving me error, “invalid property id”.
This is the jQuery code I have. I have a php function in function.php that stores the custom field data in array and do foreach loop to display. I want to pass a int var, so that it will display or add 5 custom fields per click. In the code below, I’m trying to get the var n passed to php function.
jQuery(function($){
var n = 5;
$(‘#showMore’).click(function(){
data = {action: ‘my_ajax_hook’, nonce: ‘n497slk’, var: ‘n’}
$.post(”, data, function(response){
$(‘#pullAjax’).append(response);
});
});
});
Remember that your nonce should be generated by the PHP function shown in the video, the one I used was just a quick example.
Your code should also just use
nwithout the quotes as it is a variable & you want to send the value (which is 5) not the string literal (which is n).The error I can only assume is due to the missing path. Your post function should use the path shown in the video, all AJAX calls in WP must be routed through the WP AJAX file to help prevent malicious attacks etc.
One small question since I’ve never seen that error before, is it given by Javascript or PHP?
Sorry about quotes, I was trying to figure out the error since I’m not familiar with javascript. The error is given to javascript code.
I added, “check_ajax_referer(‘my_ajax_function’, ‘nonce’);” in the first line after function header in php.
And this, “data = {action: ‘my_ajax_hook’, nonce: ”}” This doesn’t give me error in the IDE (netbeans), but it gives me php fatal error on the page.
“Cannot redeclare custom_field() (previously declared in…”
custom_field() is name of my php function. Now I can’t even go back to the page or admin. I think it has something to do with the server not letting me save the file as they always have problems.
I’m not sure about the javascript error. The fatal error is because you seem to have named your function the same as a previously declared one (probably by WordPress). The only way to get back into your site is to grab your file via FTP, fix the error and reupload it. It sometimes happens if you accidentally create a error when editing inside the WordPress file editor.
That is the cause of your PHP error though, I’m not sure about the Javascript error though. I’ve never came across it before.
I got the check_ajax_referer working. The error cause was that the server was appending the file and not overwriting it to save. I didn’t realize until the file was 100kb lol I use fireFTP.
I will try to figure out what is this javascript error.
Thank you for your time!
Ahh okay, never had that happen before. Naughty server.
Apparently the error is caused by incorrectly formatting JSON or a javascript object, so I’d say check that there are commas & colons in the correct places in the line that defines your data. Other than that I’m not sure.
I got it working! I was literally typing
var: n,
while it was supposed to be
n: 5,
And I caught it as $_POST variable on php like you said. Thanks a lot again! Great tutorial and great help!
Great glad you’ve gotten it working.
No problem & glad the tutorial was helpful.
Sorry, I hit another wall. When I output the value from php function, it displays -1 in browsers except FireFox works perfect. I just echo with foreach loop in php function. Do you have any suggestion?
Thanks
That’s normally returned by WP if the nonce doesn’t validate properly. I’ve no idea why it would work in FF though.
I see. Can you see if I’m missing anything? This javascript code is right after wp_head().
jQuery(function($){ var n = 4; var n2 = 2; $('#showMore').click(function(){ data = {action: 'my_ajax_hook', nonce: '<?php echo wp_create_nonce('my_ajax_function'); ?>', n: n, n2: n2} $.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function(response){ $('#pullAjax').append(response); n2 = n; n++; }); }); });add_action('wp_ajax_my_ajax_hook', 'thecustom_field'); function thecustom_field(){ check_ajax_referer('my_ajax_function', 'nonce'); $n = $_POST['n']; $n2 = $_POST['n2']; $myarray = array_reverse(get_post_meta(2,"Testimonial", false)); foreach ( $myarray as $key => $value ){ if ($key < $n && $key >= $n2){ echo "<li>$value</li>"; } } die(); }Thanks.
The second part from add_action… is my php code in function.php.
And I’m sorry, I keep messing the order of comments by missing the reply button.
I found the solution, so I will post here. You have to add the second function below for users not logged in. That’s why it would not show in my other browsers. It’s explained in wordpress codex.
add_action(‘wp_ajax_my_action’, ‘my_action_callback’);
add_action(‘wp_ajax_nopriv_my_action’, ‘my_action_callback’);
Thanks again for all.
I’m not sure why you’d need two like that, although all my dealings with AJAX in WordPress have been done in the Admin so you would already be logged in.
I’ll have a play around & see if I can explain why that would happen.
Hi! should tell You about error in loading video “this playlist is not a valid xml file”
Thanks FelixFett,
just a little problem with the plugin I use for the video & an upgrade. All fixed now.