0

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?

1 Answer 1

1

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;
  }

}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Emiel an thanks for you help, I have these actions after my php function, my code is this: ``` function update_status(){ echo"<script>alert('I am update function!!!!');</script>"; } add_action('wp_ajax_update_status', 'update_status'); add_action('wp_ajax_nopriv_update_status, 'update_status'); ``` Should my php function name be after wp_ajax and wp_ajax_nopriv?
Yes whatever comes after wp_ajax and wp_ajax_nopriv is the name of the action. So in your AJAX request you should send action=update_status to call that hook. For example: wp_ajax_nopriv_foobar should be called from AJAX with ?action=foobar. That's how WP knows which function you want to call on the server. I do however would advice against sending back HTML with JavaScript as a response, as you are already receiving a response in JavaScript and can determine what to do from there based on the response.
Ok, I have another question, how can I use an action without a form, I am working from a modal, I have a list of items and I need to delete an item when the user presses the delete button, after that I want to delete the selected item from my table in my database, and I thought that a form is not needed to perform this task, and my problem is that it did not have an action, if possible where can I add an action without using a form?
Well, you already built something like this above here in your question, right? Just create another hook and use AJAX to call this hook. You can send any kind of data with you to the hook.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.