converting json array to php to request a webservice - javascript

I am currently programming a webservice. on of its method is to send some information to delete a user from event. this is documentation:
the json is like this
{
"users": "[users :['userid' : 1, 'role' : 'participant'],['userid' : 2, 'role' : 'teacher'],['userid' : 3, 'role' : 'assistant']]"
}
but I always get the error of "field users is required";
I appreciate any answer. thanks alot
I tried this
function delete_user_from_event( $event_id, $user_id ){
$webService = 'https://pnlapi.alocom.co/api/v1/agents/events/'. $event_id .'/remove-users';
$params = array(
'users' => array(
'users' => array(
[
'userid' => $user_id,
'role' => 'participant',
] )
)
);
return $this -> post_request( $webService, false, $params, 'patch' );
}
but I get error. I think I do not understand json array.

Related

Jetpack shortcode and share link doesn't shows after loading next post via Ajax

I tried make in the single post infinite scroll and load next post via ajax. I am using Jetpack for displaing share links of the post and also related posts. It works nice and initialize correctly when post was opened, but, when i send the content of the next post via Ajax, Jetpack doesn't initialize and consequently doesn't show the content... I tried to initialize using filters, but it doesn't work. The post's content generates and sends before the plugin's content initialize on the template. Is there any method to wait untill the plugin will be initialized, and send the full templated only after that? Or is there any other way to make it? I tried it on different plugins, not only Jetpack, the result the same. Sorry, if question may seems to very obvious, i am begginer.
Here is my code
JavaScript
const getNextPost = () => {
const bottomOffset = 1500,
loadBtn = $("#loading"),
main = $(".site-main"),
article = $("article"),
category = article.data("category");
let paged = 1;
$(window).scroll(function() {
if (
$(document).scrollTop() > $(document).height() - bottomOffset &&
!$("body").hasClass("loading") &&
category
) {
$.ajax({
type: "POST",
url: horisont.ajaxurl,
data: {
paged: paged,
category: category,
action: "loadnext",
},
beforeSend: function(xhr) {
console.log(category);
$("body").addClass("loading");
loadBtn.show();
},
success: function(data) {
let items = $(data);
paged++;
main.append(items);
loadBtn.hide();
$("body").removeClass("loading");
},
});
}
});
};
Php ajax
function loadnext_post() {
$category = ! empty( $_POST[ 'category' ] ) ? $_POST[ 'category' ] : '';
$paged = ! empty( $_POST[ 'paged' ] ) ? $_POST[ 'paged' ] : 1;
$paged ++;
$next_query = new WP_Query([
'p' => $next_id,
'post_type' => ['news', 'interview', 'post', 'post-analitiki'],
'posts_per_page' => 1,
'paged' => ($paged===1) ? 1 : $paged,
'category_name' => $category,
]);
while( $next_query->have_posts() ){
$next_query->the_post();
$jprp = Jetpack_RelatedPosts::init();
$callback = array( $jprp, 'filter_add_target_to_dom' );
add_filter( 'the_content', $callback, 40 );
get_template_part( 'template-parts/content', 'single-news' );
}
wp_reset_postdata( );
die;
}
add_action( 'wp_ajax_loadnext', 'loadnext_post' );
add_action( 'wp_ajax_nopriv_loadnext', 'loadnext_post' );

AJAX pagination not loading in new posts (admin-ajax not found)

I have a custom post type built in WordPress named Knowledge.
Knowledge currently only has 4 posts in total. By default, 3 posts are shown, then on load more click, I want the last, 4th blog card to show.
However, currently, my AJAX request isn't succeeding, it gives me the /wp-admin/admin-ajax.php 403 (Forbidden) error. Similar questions stated that it might be related to security plugins. However, I have disabled any security related plugins (Jetpack) and the error still exists.
Here is my approach so far:
knowledge-listing.php
<?php
global $post;
$args = array(
'post_type' => 'knowledge',
'posts_per_page' => 3,
'post_status' => 'publish',
'orderby' => 'publish_date',
'order' => 'DESC'
);
$query = new WP_Query($args);
if ($query->have_posts()):
while ($query->have_posts()):
$query->the_post();
get_part('templates/snippets/knowledge-card', array(
'heading' => get_the_title() ,
'subheading' => get_the_excerpt() ,
'background' => wp_get_attachment_url(get_post_thumbnail_id($post->ID)) ,
));
endwhile;
wp_reset_postdata(); ?>
<div class="knowledgeListing__loadmore">
<a href="#" id="loadmore" class="button--loadmore" data-type="knowledge" data-max-num-pages="<?php echo $query->max_num_pages; ?>">
<?php echo _e('Load More', 'theme'); ?>
</a>
</div>
<?php
endif; ?>
loadmore.js
jQuery(function($){
$(document).ready(function(){
$("#loadmore").on('click', function (e) {
e.preventDefault();
var btn = $(this);
showNextItems(btn);
});
function showNextItems(btn) {
var max_num_pages = btn.data('max-num-pages');
var post_type = btn.data('type');
var button = btn,
data = {
'action':'loadmore',
'query': loadmore_params.posts,
'page' : loadmore_params.current_page,
// 'security' : loadmore_params.security,
// 'max_num_pages' : max_num_pages,
// 'post_type' : post_type
};
$.ajax({
url : loadmore_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...');
},
success : function( data ){
if( data ) {
button.text( 'Load More' ).prev().before(data);
loadmore_params.current_page++;
$('.knowledgeListing__wrapper').find('.knowledgeCard').last().after( data );
if ( loadmore_params.current_page == max_num_pages ){
button.remove();
}
console.log("success");
} else {
button.remove();
}
},
error : function(error){
button.text( 'Load More' );
console.table("Data: " + data);
console.table("loadmore_params: " + loadmore_params);
// console.log(error);
}
});
}
});
});
The following two console.log's spit out [object Object]
console.table("Data: " + data);
console.table("loadmore_params: " + loadmore_params);
Unsure where things are going wrong?
Edit:
console.log("Data:", data) and console.log("loadmore_params:", loadmore_params); results below:
On further inspection, when trying to access the /wp-admin/admin-ajax.php url, I see a 0. When searching for this online, it has been suggested to use die(). However, when I've added die() to the end of knowledge-listing.php, it still shows me a 0.
Here is my localized script for reference:
global $wp_query;
wp_localize_script( 'theme', 'loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'posts' => json_encode( $wp_query->query_vars ),
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages,
'security' => wp_create_nonce("load_more")
) );
And actions:
add_action('wp_ajax_loadmore', 'pagination_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'pagination_ajax_handler'); // wp_ajax_nopriv_{action}
Just my 2 cents but "loadmore" as an action name is quite common and may be used by some other plugins/theme function. You should really consider switching to something namespaced like wp_ajax_mypluginname_loadmore.
That said, another common issue is that you perform the add_actions too late or maybe they never get hit by code before wp-admin-ajax does his thing.
Please be 100% you hit the add_actions BEFORE the code enter wp-admin-ajax.
To make a quick test you could move those line (included the function) in your child-theme functions.php file

Cannot create custom fields with the wpapi Node.js wrapper for WordPress REST

I use the following snippet to create a WordPress post via the REST API, using the Node.js wrapper:
var wp = new WPAPI({
endpoint: 'http://your-site.com/wp-json',
username: 'someusername',
password: 'password'
});
wp.posts().create({
title: 'Your Post Title',
content: 'Your post content',
status: 'publish',
meta: { "custom_field": "my custom field value" }
}).then(function( response ) {
console.log( response.id );
})
When fetching the posts, the meta is empty.
Why is that and how can I fix that?
For some reason that did not work for me either. I ended by using a WordPress REST hook.
In functions.php I added:
add_filter( 'pre_post_update' , function ( $post_id , $post ) {
$body = json_decode(file_get_contents('php://input'), true);
$meta_fields = $body["meta"];
foreach ($meta_fields as $meta_key => $value) {
update_post_meta($post_id, $meta_key, $value);
}
}, '99', 2 );
The snippet above will parse the meta field and will update the post metadata fields.
If you want to include the custom fields in the responses, you can use:
//Get custom fields via Rest API
add_action( 'rest_pre_echo_response', function( $response, $object, $request ) {
//* Get the post ID
$post_id = $response[ 'id' ];
if ($response['type'] !== 'post' && $response['type'] !== 'page') return $response;
$response['custom_fields'] = get_post_meta($post_id);
return $response;
}, 10, 3 );

WordPress - How to alphabetically order jQuery AutoComplete search suggestion results, prioritizing first character, then second etc.?

I'm using jQueryUI AutoComplete with WordPress to fetch terms of a custom taxonomy as a user types in a search box.
I have a lot of sports brands as custom taxonomy terms, so, for example, the term Adidas can have many subterms. Now when I type a, it displays...
Adidas
Adidas Shoes
Adidas Socks
etc...
...causing the other brands to get in the dark. So, when I type a, I would like the results to show as follows...
Adidas
Amphipod
Asics
etc...
...until I continue typing ad, and only then should the Adidas results with the subterms appear, like in the first example. Is this possible to accomplish? Is jQueryUI AutoComplete able to order the results for me like this, or do I need to sort them on the server side with a PHP function like sort, usort etc.? I've tried to write a few different PHP sort functions to no avail so far, but I really have no idea right now.
This is the code I have right now:
autocomplete.js
$(function() {
var url = MyAutocomplete.url + "?action=my_search";
$('.search-field').autocomplete({
source: url,
delay: 500,
minLength: 2,
sortResults: true
})
});
functions.php (WordPress)
function my_search()
{
$args = array(
'search' => strtolower($_GET['term']),
'taxonomy' => array('suggestion_string'),
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'number' => 10,
);
$search_query = new WP_Term_Query($args);
$results = array( );
if ( $search_query->get_terms() ) {
foreach($search_query->get_terms() as $term) {
$results[] = array(
'label' => $term->name,
);
}
}
else {
}
// Tried to write a few different sort functions here to no avail, like:
sort($results);
$data = json_encode($results);
echo html_entity_decode( $data );
exit();
}
add_action( 'wp_ajax_my_search', 'my_search' );
add_action( 'wp_ajax_nopriv_my_search', 'my_search' );
Everything is possible my friend you just have to code it as you wish. You can achieve what you want on the server side as well as on the client side, in this case I would recommend the server side though.
If you do not want autocomplete show subcategories just do not deliver those. Either you eliminate names starting with the same word first or you exclude subcategories. Here is my code for you for the first possibility:
function my_search()
{
$args = array(
'search' => strtolower($_GET['term']),
'taxonomy' => array('suggestion_string'),
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'number' => 10,
);
$search_query = new WP_Term_Query($args);
$results = array( );
if ( $search_query->get_terms() ) {
foreach($search_query->get_terms() as $term) {
$results[] = array(
'label' => $term->name,
);
}
}
else {
}
$filtered = [];
$existing = [];
if(strlen($_GET['term'])<2) {
foreach($results as $term) {
$first_word = explode(" ",$term["label"])[0];
if(!in_array($first_word,$existing) {
array_push($existing,$first_word);
$filtered[] = $term;
}
}
} else {
$filtered = $results;
}
$data = json_encode($results);
echo html_entity_decode( $data );
exit();
}
add_action( 'wp_ajax_my_search', 'my_search' );
add_action( 'wp_ajax_nopriv_my_search', 'my_search' );

wordpress custom query - orderby title will not work

I am having a problem getting a custom query to alphabetize. It keeps defaulting to displaying in the order of the date it was posted. Below is my php function.
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for each of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','machinery');
$statesAll = array('SC','TX','WA');
// set $statusArray dependent on whether or not "all" is selected in the dropdown menu
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
<li>
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
?>
This above function is called by the ajax function that follows:
function do_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
Is there something simple that I'm missing here? I have a similar custom query on the page when it loads (although that initial load query doesn't have the select menu values as args), and they display in alphabetical order just fine. It's only after the ajax call to filter the list that they are no longer in order.
I have found the issue after googling the problem for quite a while. I read that some of the people who were having this problem found that their theme was using a plugin called Post Types Order. It overrides the ability to set the orderby arg.
I looked at the plugins, and sure enough, Post Types Order was there. Everything I read said that the problem could be solved by unchecking "auto sort" in the settings for the plugin. However, I did that, and orderby still didn't work. I had to completely deactivate the plugin to get orderby title to work.

Categories

Resources