As you can see the $.ajax() function is what we’re using here. There are special functions for post and get methods but I prefer using this function because of its flexibility. You can read about all the parameters in the jQuery Documentation. Using the url parameter we pass the URL of the script we want to send data to. This should be the admin-ajax.php file which can be found in the wp-admin directory. We defined this above via the wp_localize_script() function. The type is set to post. We could also use get, our query is not too sensitive but I prefer to post data unless the user needs access to the parameters. The data parameter is an object which contains the data you want to pass. In our case I will be able to access a $_POST['action'] variable, the value of which would be ajax_pagination. You can pass as many as your application requires of course.
0 is returned if no server-side code is written.
Finally, the successparameter is a function which alerts the result of our AJAX call. We’ll make this a bit fancier below, for now this is sufficient for testing. If you try clicking on a link now it actually works but won’t be very useful since we haven’t defined the server side code. In fact, what you should see alerted is 0. So why does this happen? When I said “we haven’t defined server side code,” I wasn’t entirely truthful. We haven’t, but WordPress has. There is some content in the admin-ajax.php file we are using. If you take a look at the source code of that file you should see that the script uses die( '0' ) in a couple of cases. If we don’t supply an action the admin-ajax.php script dies and returns 0. If we do supply an action but we don’t hook into the required WordPress hooks nothing happens and at the very end of the file we die again, returning 0. In conclusion we are already communicating with the server.

Communicating With WordPress

To get a meaningful answer from WordPress we need to define some WordPress actions. This is done using a set pattern. Let’s dive in by continuing our example in the functions file of our theme:

Solo para miembros

Si tienes problemas para acceder, solicita vía telegram asistencia técnica aqui