I am developing a WordPress plugin, and everything works fine. Only problem is, I have an ajax call in jQuery to some code in a php file. It works but it is just a few php commands in a file. That is bad practice in WP, everything should be in a function and attached using a hook.
this is the code in output.php
if(isset($_POST['test']) && $_POST['test'] == 'ON'){
if(isset($_POST['id'])){
$productId = intval(preg_replace('/[^0-9]+/', "", $_POST['id']));
if ($productId > 1){
$results = get_option( 'test_options' );
$result = $results[$productId];
unset($results);
echo json_encode($result);
die();
}
}
}
this is the AJAX-call in jQuery script
$.ajax({
type: "POST",
url: "output.php",
data: {
'test' : "ON",
'id' : productId
},
success: function(results) {
result = $.parseJSON(results);
createArray(result);
}
});
This works fine. But when I change the code in output.php into a function and use action hook like this:
function getInfo(){
$test = $_POST['test']);
$id = $_POST['id']);
if(isset($test) && ($test == "ON")){
$result = '';
if(isset($id)){
if ($id > 1){
$results = get_option( 'test_options' );
$result = $results[$id];
echo json_encode($result);
die();
}
}
}
}
add_action('wp_ajax_getInfo','getInfo');
add_action('wp_ajax_nopriv_getInfo','getInfo');
and change the jQuery script to:
$.ajax({
url: my_ajax_script.ajaxurl,
type: 'POST',
data: {
action : 'getInfo',
test : "ON",
id : productId
},
cache: false,
success: function(results) {
result = $.parseJSON(results);
console.log(result);
alert("succes");
createArray(result);
}
});
it doesn't work. What am I missing? I have checked a lot of questions on stackoverflow describing sort of the same problem, checked the solutions but can't find where I go wrong.
It finally started working once I added the code of the output.php file to the file that held the wp_localize_script() command for the AJAX url.
For frontend use of AJAX calls you need this command to make AJAX available. In admin area AJAX is available by default.
Related
WordPress
I have a ajax function passing value to a function in functions.php
The function on functions.php sends the response to ajax success but the value I am passing using ajax is not going to the function in functions.php
$.ajax({
url: ajaxStuff.ajaxurl,
type: "GET",
processData :true,
data: {
action: 'filter_package',
value: data,
},
success: function (data) {
alert(data);
},
});
The console.log for data shows as:
{cat_names: Array(1), reg_names: Array(0), dest_names: Array(0), fromPrice: '', toPrice: '', …}
which is correct one.
If I enter some hardcoded message to my filter_package function in functions.php the ajax shows the response which means the ajax function hits my function on functions.php but when I try to get the data from ajax on my function I shows Array0
function filter_package()
{
$value = $_REQUEST['value'];
$cat_slug = $value['cat_names'];
echo 'sadasd'.$cat_slug;
The output:
sadasdArray0
check your ajax url and make sure admin.ajax hit correctly in networkbdev tools
also can check Ajax call to PHP action/function with array as data (in wordpress)
I have heard promising words about php's Swoole project. However, in their doc/examples, I only see the implementation of server handlings (i.e. how to setup webserver, answer requests, etc..). However, I was unable to find examples, how to simply fire an asynchronous functions from cli (i.e. php myfile.php)
where myfile.php might contain (with my undestranding) something like this Swoole\SomeAsyncFunion (just phseudo name):
Swoole\SomeAsyncFunion( function(){ file_get_contents("http://site-1.com"); echo "hello"; } );
Swoole\SomeAsyncFunion( function(){ do_long_running_function(); echo "world"; } );
Swoole\SomeAsyncFunion( .... );
Swoole\SomeAsyncFunion( .... );
Swoole\SomeAsyncFunion( .... );
So, just execute multiple functions in async from php-cli. How to do that? With parallel extension I exactly same as described ( \parallel\run( function(){ ... } ); ) but couldn't figure-out how to do with swoole. (i dont have a requirement of any web-server, just need cli).
you can use Co\run and go
use function Swoole\Coroutine\go;
use function Swoole\Coroutine\run;
run(function () {
go(function () {
file_get_contents("http://site-1.com"); echo "hello";
});
go(function () {
do_long_running_function(); echo "world";
});
});
I have spent two days trying to figure this out. I have wordpress page with a four field Ninja Form. One of the fields is an Email. I created an API (in our .NET Core project) that checks and then throws a 400 error if a already with that email address exists in our DB. I am using the Ninja Forms Webhook feature to submit the form to my API. I just want to display my 400 error message to the user.
I am using the documentation below from Ninja Forms but it is not working:
https://developer.ninjaforms.com/codex/custom-server-side-validation/
More specifically, I am getting a 500 with the the following error in the console:
Uncaught Error: Call to undefined function my_nf_validation() in \/home\/site\/wwwroot\/wp-content\/themes\/hello-elementor\/functions.php:245\nStack trace:\n#0 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): {closure}(Array)\n#1 \/home\/site\/wwwroot\/wp-includes\/plugin.php(206): WP_Hook->apply_filters(Array, Array)\n#2 \/home\/site\/wwwroot\/wp-content\/plugins\/ninja-forms\/includes\/AJAX\/Controllers\/Submission.php(132): apply_filters('ninja_forms_sub...', Array)\n#3 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): NF_AJAX_Controllers_Submission->submit('')\n#4 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(311): WP_Hook->apply_filters('', Array)\n#5 \/home\/site\/wwwroot\/wp-includes\/plugin.php(478): WP_Hook->do_action(Array)\n#6 \/home\/site\/wwwroot\/wp-admin\/admin-ajax.php(175): do_action('wp_ajax_nf_ajax...')\n#7 {main}\n thrown<\/pre>"},"last":{"type":1,"message":"Uncaught Error: Call to undefined function my_nf_validation() in \/home\/site\/wwwroot\/wp-content\/themes\/hello-elementor\/functions.php:245\nStack trace:\n#0 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): {closure}(Array)\n#1 \/home\/site\/wwwroot\/wp-includes\/plugin.php(206): WP_Hook->apply_filters(Array, Array)\n#2 \/home\/site\/wwwroot\/wp-content\/plugins\/ninja-forms\/includes\/AJAX\/Controllers\/Submission.php(132): apply_filters('ninja_forms_sub...', Array)\n#3 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): NF_AJAX_Controllers_Submission->submit('')\n#4 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(311): WP_Hook->apply_filters('', Array)\n#5 \/home\/site\/wwwroot\/wp-includes\/plugin.php(478): WP_Hook->do_action(Array)\n#6 \/home\/site\/wwwroot\/wp-admin\/admin-ajax.php(175): do_action('wp_ajax_nf_ajax...')\n#7 {main}\n thrown","file":"\/home\/site\/wwwroot\/wp-content\/themes\/hello-elementor\/functions.php","line":245}},"debug":[]}
I placed the code in the function.php file in Themes Editor. This is my first time working with wordpress so I hope I am doing this right. This is my code and is taken directly from the above documentation:
add_filter( 'ninja_forms_submit_data', function( $form_data ){
if( ! my_nf_validation( $form_data ) ) { // Add check here.
$errors = [
__( 'An unexpected error occurred.', 'my-plugin' )
];
$response = [
'errors' => $errors,
];
echo wp_json_encode( $response );
wp_die(); // this is required to terminate immediately and return a proper response
}
// If no errors, be sure to return the $form_data.
return $form_data;
});
I would really appreciate anyone's help with this.
Try the following Code, It will work.
function validateCode($field){
if( checkCondition ){
// let it go
return true;
}
else{
return false;
}
}
add_filter( 'ninja_forms_submit_data', 'my_ninja_forms_submit_data' );
function my_ninja_forms_submit_data( $form_data ) {
$form_settings = $form_data[ 'settings' ]; // Form settings.
if($form_data['id'] == '2'){
foreach( $form_data[ 'fields' ] as $field ) { // Field settigns, including the field key and value.
if( 'unique_code' == $field[ 'key' ] ){
if(!validateCode($field)){
$form_data['errors']['fields'][$field['id']] = "INVALID CODE";
}
}
}
}
return $form_data;
}
The documentation references a custom WordPress filter, as defined by the Ninja Forms plugin. Filters are a feature of WordPress Hooks, which allow a theme or plugin to modify the functionality of another theme or plugin. See https://developer.wordpress.org/plugins/hooks/filters/
To your question, the Webhooks add-on plugin (an official extension of Ninja Forms) is not required to use the filter that you reference from the documentation.
Instead, you'll need to replace "my_nf_validation()" with your own defined function, as the documentation shows an example.
Your function needs to handle the API request and response handling. In the documentation example, the custom function returns a Boolean value.
A custom endpoint like this
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
Using basic authentication in headers, let's say 'Authorization: Basic some64basePass'
How I can check the value of Authorization in the header is valid or not?
Here is my solution.
Inside the callback function I validate Authorization from the header like this:
function my_awesome_func($data) {
//Get HTTP request headers
$auth = apache_request_headers();
//Get only Authorization header
$valid = $auth['Authorization'];
// Validate
if ($valid == 'Basic Base64UsernamePassword') {
//Do what the function should do
} else {
$response = 'Please use a valid authentication';
}
return json_encode($response);
}
Maybe there is a better way.
WordPress has a hook for adding your own authentication handler.
add_filter( 'rest_authentication_errors', 'rest_basic_auth_check_errors', 99 );
Your rest_basic_auth_check_errors() should return true if basic authentication succeeds or WP_Error if it fails. Since the default REST authentication handler runs at priority 100 your rest_basic_auth_check_errors() will override the default handler.
See the function WP_REST_Server::check_authentication() in file ...\wp-includes\rest-api\class-wp-rest-server.php to understand how WordPress handles REST authentication and how to add your own authentication handler.
Also, you should read about $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] in http://php.net/manual/en/features.http-auth.php
I'm writing an application to receive and process an Instant Payment Notification message in wordpress. It is a POST request made to a "virtual" url with rewrite rules. The problem however is that only GET vars are acessible, I cannot access the post variable:
Both:
print_r($wp->query_vars['ccustfirstname']);
print_r($_POST);
Result in an empty array
I've modified existing code to match my case:
function ao_add_rewrite_rule() {
print_r($_REQUEST);
$ipn_parameters=array("ccustfullname","ccustfirstname", ... );
foreach ($ipn_parameters as $key => $value) {
add_rewrite_tag("%$value%",".");
}
add_rewrite_tag("%arevico_api%",".","");
add_rewrite_rule( 'ipn', 'index.php?&arevico_api=ipn', 'top');
add_rewrite_rule( 'hoplink', 'index.php?&arevico_api=hop', 'top');
add_rewrite_rule( 'pay', 'index.php?&arevico_api=pay', 'top');
flush_rewrite_rules();//TODO: call only when needed
}
add_action( 'parse_request', 'wpse9870_parse_request' );
function wpse9870_parse_request( &$wp )
{
if (!empty($wp->query_vars['arevico_api'])) {
switch ($wp->query_vars['arevico_api']){
case "ipn":
print_r($wp->query_vars['ccustfirstname']);
print_r($_POST);
die();
// require_once(AREVICO_PLG_BP . "ipn.php");
// $ArevicoIPN=new ArevicoIPN();
break ;
default:
break;
}
}
return;
}
Please note that the arevico_api get parameter does get trough, but the POST parameters don't. I'm testing the application by sending a sample post data trough Simple Rest Client for chrome. How do I get to access thhe post parameters