PHP Scripts for use jQuery and AJAX in WordPress

Mar 20, 2012, by admin

In the following snippets of code, we will show you how to execute the use of jQuery and AJAX in your WordPress installation (typically in your own custom plugin). The first bit of code you will need is to make sure that you load the jQuery library.Since WordPress comes with jQuery and AJAX already bundled, you can make sure it is loaded by first setting up an action for WordPress to comprise the jQuery library. The below example uses the admin print scripts action, which will obviously only run in the admin section of WordPress. You may change this based on your needs.

1    jQuery(document).ready(function($) {

2

3       $(‘#someElementId’).live(‘click’, function() {

4            var dataRequest = ({action: “yourWordPressAjaxFunction”,

5                        someparam: somevalue,

6                        seed: Math.random()});

7

8            $.ajaxSetup ({

9                cache: false,

10                async: false

11            });

12

13            $(“#preloader”).html(‘<p><img src=”loader.gif” alt=”” /></p>’);

14

15            $.get(ajaxurl, dataRequest, function(data){

16

17                if (data.returnError != “success”) {

18                    divContent = ‘<p> + data.returnError + ‘</p>’;

19                    $(“#someDivId”).empty().append( divContent );

20                } else {

21                            divContent  = ‘<p><strong>FINISHED</strong></p>’;

22                            divContent  += ‘<p><strong>VAR1: ‘ + data.someValue1 + ‘</strong></p>’;

23                            divContent  += ‘<p><strong>VAR2: ‘ + data.someValue2 + ‘</strong></p>’;

24                            $(“#preloader”).empty().append( divContent );

25                }

26            }, “json”);

27        });

28    });

 

&nbsp;