Skip to content
Advertisement

How can I call a php function from ajax in wordpress?

I am new to wordpress and I need to call a php function from ajax but my code is not working. I was reading about the ajax standard in wordpress, but I don’t know what happens, I have followed several tutorials and answers in this blog and they all talk about the action to enqueue the javascript file, but the problem continues and I don’t know what I’m doing wrong. To continue I share my code.

This is my function to enqueue my javascript file:

JavaScript

My php function to call, this is in an update_request_status.php file:

JavaScript

This is my js action, :

JavaScript

And finally, this is my modal with the button that triggers the action to call my php function:

JavaScript

Can somebody help me?

Advertisement

Answer

There are multiple ways to do it. First I’ll show the one you were working on.

You’ll need to define two actions with wp_ajax_{action} and wp_ajax_nopriv_{action}, where {action} is a placeholder for a keyword to identify the function that needs to be called. The former is only works when users are logged in. The latter is for request from unauthenticated users.

Both hooks should refer to the same function that you are trying to call.

The example below returns either the request_id that has been sent or a string with 'Nothing' as a response, just to test things out.

JavaScript

The other, and more modern approach is using the REST API. This enables you to create an endpoint where you get more controls over de URL and sanitizing.

Your endpoint would look something like this https://yourwebsite.com/wp-json/api/v1/update. You can get the static URL to the REST endpoint by using get_rest_url(), like you did with admin_url( 'admin-ajax.php' ) and should add that to your wp_localize_script function in the enqueue file.

The endpoint checks the methods allowed and calls the callback specified in the options array. From there you can access the $request object which contains info like the given arguments from your request.

Then return a response to read on the frontend.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement