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:

function enqueue_script() {
    $ajax_script = 'popup';
    $uri = get_stylesheet_directory_uri() . '/assets/front/js/popup.js';
    wp_register_script($ajax_script, $uri);
    wp_localize_script( $ajax_script, 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
    wp_enqueue_script( $ajax_script, $uri, array('jquery'), rand(111,9999), 'all');
}
add_action( 'wp_enqueue_scripts', 'enqueue_script' );

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

function update_status(){
    echo "<script>alert('I am update function!!!!');</script>";
}

This is my js action, :

$('.btn-confirm').click(function(){
     var url_string = window.location.href;
     var url = new URL(url_string);
     var request_id = url.searchParams.get("request_id");
     $.ajax({
       url: ajax_object.ajaxurl,
       type: 'POST',
       cache: false,
       data: { "request_id": request_id } + '&action=change_status',
       success:function(data){
         alert("YEs I doing");
       },
       error:function(){
         alert("¡Error en el servidor, contancte al administrador!");
       }
     });
     window.location.href = "http://localhost:8081/megafrescos/pendientes";
     $('#msg-remove-request').css('display', 'none');
  });

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

<div class="warning-msg" id="msg-remove-request">
  <button class="btn-close"  id="btn-close">&times;</button>
  <h5>¿Dar por concluida esta solicitud ? </h5><hr>
  <?php echo  fix_request()?>
  <div class="confirm-btns">
    <button class="btn-confirm">Aceptar</button>
    <button class="btn-close">Cancelar</button>
  </div>
  <div class='update-status'></div>
</div>

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.

add_action( 'wp_ajax_nopriv_update_status', 'update_status' ) ;
add_action( 'wp_ajax_update_status', 'update_status' );
function update_status() {
  $request_id = isset( $_POST[ 'request_id' ) ) ? 
    $_POST[ 'request_id' ) : 
    'Nothing';
  echo $request_id;
}

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.

add_action( 'rest_api_init', 'register_update_endpoint' );
function register_update_endpoint() {

  // Register new route to get data from
  register_rest_route( 'api/v1', // Mandatory prefix with version
    '/update/', // Name of the route, can be anything.
    array(
      'methods'   => array( 'POST' ), // Allowed methods.
      'callback'  => 'update_status' // Function to call when URL is called.
    ) 
  );

  function update_status( WP_REST_Request $request ) {
    $request_id = $request->has_param( 'request_id' ) ?
      $request->get_param( 'request_id' ) :
      'Nothing';
    $response = new WP_REST_Response( $request_id; );
    return $request_id;
  }

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