0

I need to execute the Php function from my Ajax form with the POST method. Is there another way instead of ajax hooks?

Hooks doesn't execute. Always returning 0. What's wrong?

enter image description here

enter image description here

Here's my ajax.js

'use strict';

const url = test.ajaxUrl;
const data = { 
  action: 'ajax_request',
  username: 'example' 
};

async function Start(url, data) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json'
      }
    });
    const json = await response.json();
    console.log('Success:', JSON.stringify(json));
  } 
  catch (error) {
    console.error('Error:', error);
  }
}

Start(url, data);

functions.php

add_action( 'wp_enqueue_scripts', 'enqueue_my_frontend_script' );

function enqueue_my_frontend_script() {
        wp_enqueue_script( 'script-ajax', get_template_directory_uri() . '/assets/js/ajax.js', array(), null, true );
    $variables = array(
        'ajaxUrl' => admin_url( 'admin-ajax.php' )
    );
    wp_localize_script('script-ajax', "test", $variables);
}

function handle_ajax_request(){
    $postData = file_get_contents('php://input');
    $data = json_decode($postData);

    echo json_encode($data);
    die();
}

add_action("wp_ajax_ajax_request" , "handle_ajax_request");
add_action("wp_ajax_nopriv_ajax_request" , "handle_ajax_request");
1

1 Answer 1

-1

You can add a WordPress Rest API custom endpoint Docs

1
  • Thank you a lot!
    – Predaytor
    Commented Jan 28, 2020 at 10:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.