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)
Related
I am trying to post comments to my posts using the Wordpress JSON API but I keep getting an error.
Heres what I have done:
I have added the 'rest_allow_anonymous_comments' function
add_filter( 'rest_allow_anonymous_comments', '__return_true' );
Then went to the URL
https://example.com/wp-json/wp/v2/comments?post=192&author_email=mytestemail#gmail.com&author_name=TestName&content=ThisIsTestContent
But it just returns the error:
{"code":"rest_forbidden_param","message":"Query parameter not permitted: author_email","data":{"status":401}}
Does anyone know what I am doing wrong?
First of all, You have to create a endpoint for comment.
add_action('rest_api_init', function () {
register_rest_route( 'mycomment/v1', 'comment/(?P<post_id>\d+)',array(
'methods' => 'POST',
'callback' => 'post_comment'
));
});
Then the post_comment in callback will point it to another function to create another function for your logic. In this call back function, you can add your comment using wp_insert_comment().
function post_comment($request) {
// Your code here
}
Enjoy!
My PHP script isn't receiving anything via POST from fetch. What am I doing wrong?
Javascript:
fetch("http://127.0.0.1/script.php", {
method: "post",
body: "inputs=" + JSON.stringify({param: 7})
}).then(response => response.json()).then(response => {
console.log(response);
});
script.php:
echo "\nprinting POST:\n";
print_r($_POST);
echo "\nprinting GET:\n";
print_r($_GET);
die();
Console:
printing POST: Array ( )
printing GET: Array ( )
You're not adding any url parameters (hence $_GET is empty) and you're not setting a Content-Type header that will make PHP automatically parse the request body. (hence $_POST is empty).
There was something wrong with the htaccess file for that particular test PHP file. I've used it for posting something to the main project folder/PHP files and it went ok.
Been some time since I last looked at Angularjs. I have a simple get that calls an ASP.NET Controller and returns a Json object - the get is triggered but nothing is getting populated on the view. The Json object shows in the browser, so it's purely a JS Angular thing. I know I am missing something simple, but I can't quite put my finger on it. If someone would be kind enough to show what I'm missing preferably with an example that would great. I haven't been able to find a simple example, that's similar.
Angularjs.
var ngCurrent = angular.module("ngCurrent", ['ngResource']);
var ctrCd;
// Declaring a Service
ngCurrent.factory("CurrentService", function ($resource) {
return {
data: $resource("/Current/Data/:id")
}
});
ngCurrent.controller("CurrentController", function ($scope, CurrentService) {
$scope.current = CurrentService.data.get({ "id": id}, isArray = false);
});
In the CSHTML View (Condensed but all relevant rows included)
<div ng-app="ngCurrent" class="row">
<div ng-controller="CurrentController" class="col-md-1"></div>
<div class="row">
<span class="col-sm-2">{{current.RecordName}}</span>
It runs triggers the "Get" from the controller but displays no data and $scope.current contains no object.
I have had a go at JSFiddling without success here it is http://jsfiddle.net/Mark_Dete/Lfy66re1/1/
(note the Json mocking is based on http://jsfiddle.net/ExpertSystem/6PYsq/)
You can return a promise from your service like:
return $http({
url: '/api/v1/service/',
method: "GET",
headers: {'X-API-TOKEN': api_key },
params: _params
})
Then use the promise callbacks on the http object in your controller (the one returned from your service)
$scope.getApiData = function(){
Service.getData($scope.api_key)
.then(function(_data) {
console.log(_data.data);
$scope.data_obj = _data.data;
});
here's an all in one version without the service abstraction but it should work for testing.
$scope.getApiData = function(){
$http({
url: '/api/v1/service/',
method: "GET",
headers: {'X-API-TOKEN': api_key },
params: _params
})
.then(function(_data) {
console.log(_data.data);
$scope.data_obj = _data.data;
});
Make sure you remember to inject the $http dependency!
I use yepnope.js to load a polyfill (Intl). If window.Intl doesn't exist, it loads my polyfill, and executes some code. However, if windows.Intl does in fact exist, I need to execute another code, and I havn't been able to figure out how.
Here is what I have:
yepnope({
test : window.Intl,
nope : ['lib/Intl.min.js'],
callback: function(u,r,k){
$.ajax({
type: "GET",
url: 'sv-SE.json',
dataType: "json",
success: function(data) {
Intl.__addLocaleData(data,"sv-SE");
self.numberFormatter = new Intl.NumberFormat("sv-SE");
}
});
},
complete: function(){
/* Do stuff! */
The code I need to run if window.Intl already exists is self.numberFormatter = new Intl.NumberFormat("sv-SE");, but I can't figure out how, as callback is only called on false, as far as I can tell.
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.