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?
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");
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?
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");
Share
Improve this question
asked Jan 27, 2020 at 14:54
PredaytorPredaytor
33 bronze badges
1
|
1 Answer
Reset to default -1You can add a WordPress Rest API custom endpoint Docs
action
parameter. See wordpress.stackexchange/questions/338787/… – Jacob Peattie Commented Jan 28, 2020 at 15:09