The Ajax Script For Plugin
Create a .js file and call it “ytajax.js” and place it in your “ajaxyoutubesubscribe” folder. Put in the following code. This makes the Ajax call and returns the response so that your website does not reload. jQuery starts with the document ready function to make sure your webpage is loaded then it waits for someone to “Click” on your button. If they do, then it begins calling in your YouTube subscribe button. This script does not get loaded until someone clicks on your button thereby increasing your speed and scores on your website. Not to mention, giving you a really cool feature for your website visitors.
jQuery(document).ready( function() { jQuery(".ytbe_ajaxs").click( function(e) { e.preventDefault(); post_id = jQuery(this).attr("data-post_id"); nonce = jQuery(this).attr("data-nonce"); jQuery.ajax({ type : "post", dataType : "json", url : myAjax.ajaxurl, data : {action: "ytsub_ajax_call", nonce: nonce}, success: function(response) { if(response.type == "success") { jQuery("#tysub_sub").html(response.youtube_subscribe); } else { alert("Could not get form."); } } }); }); });
More WordPress Ajax Tutorials
While creating this tutorial, I found some other cool developers working on WordPress Ajax in different ways. There are 2 that stood out to me. Alex Young has implemented some great ways to use the WordPress Ajax with Rewrite and REST Api’s. Share Web Design was another where he uses Ajax to call in a script on the front end.
3 Comments
Interesting and usefull post about ajax.
Any code?
Sure, are you having an issue seeing the code that is posted?
Remember to go to the next pages. I did not put the code all on one page because of the space.