I’m trying to run a method from page controller using ajax. Here what I got until now:
On filter.php, I run the hooks:
add_action( 'wp_ajax_addBanco', ['App\PageProprietario', 'addBanco'] );
add_action( 'wp_ajax_nopriv_addBanco', ['App\PageProprietario', 'addBanco'] );
And on the controller, I wil stored the method:
public static function addBanco()
{
wp_send_json_success($_POST);
}
My question is: this is the correct way? The method must be static or could be public?
Static methods must be called differently.
Change this
add_action( 'wp_ajax_addBanco', ['App\PageProprietario', 'addBanco'] );
To this
add_action( 'wp_ajax_addBanco', ['App\PageProprietario::addBanco'] );
Thanks for the reply @codepuncher. But I believe the correct way is setting callback function outside the array. Like this:
add_action( 'wp_ajax_addBanco', 'App\PageProprietario::addBanco' );
File FrontPage.php
public static function exampleFunction()
{
$name = array(
'a' => 1,
'b' => 2,
'c' => 3
);
return $name;
}
You can use
File setup.php
namespace App;
function my_enqueue() {
wp_enqueue_script(‘sage/main.js’, asset_path(‘scripts/main.js’), [‘jquery’], null, true);
wp_localize_script( ‘sage/main.js’, ‘my_ajax_object’, array( ‘ajax_url’ => admin_url( ‘admin-ajax.php’ ) ) );
}
add_action( ‘wp_enqueue_scripts’, NAMESPACE .’\my_enqueue’ );
function callExampleFunction() {
$name = \FrontPage::exampleFunction();
wp_send_json_success($name);
}
add_action(‘wp_ajax_nopriv_call_exaple_function, NAMESPACE .’\callExampleFunction’ );
add_action(‘wp_ajax_admin_call_example’_function, NAMESPACE .’\callExampleFunction’ );
File common.js
$.ajax({
// eslint-disable-next-line no-undef
url : my_ajax_object.ajax_url,
data : {
action: ‘call_example_function’,
},
success: function(response) {
console.log(response);
},
});