I'm writing this question because I have an AJAX request for deleting posts into my website that is working fine but I have duplicated it multiple times to match the URL for different Custom Post Type that I have in the page.
Here the original code:
jQuery(".delete-listing-btn").on("click", function(e) {
var thisPost = jQuery(e.target).parents(".agent-dashboard-listing-card")
jQuery.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', msSiteData.nonce);
},
url: 'https://mallorca-select.com/wp-json/wp/v2/properties-for-sale/' thisPost.data('id'),
type: 'DELETE',
success: function () {
alert(" Listing Deleted Successfully! ");
},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " error);
}
});
});
In these functions the only thing that changes is a part of the URL request like this:
'https://example.com/wp-json/wp/v2/post-type-1/' thisPost.data('id')
'https://example.com/wp-json/wp/v2/post-type-2/' thisPost.data('id')
'https://example.com/wp-json/wp/v2/post-type-3/' thisPost.data('id')
'https://example.com/wp-json/wp/v2/post-type-4/' thisPost.data('id')
I'm wondering if there is a method for detecting the post type of the post where the delete button is clicked and inject inside the URL request so I don't have to duplicate it 4 times only to change the custom post type inside the url.
CodePudding user response:
Move the common AJAX code to a separate function and pass the specific URL you need in each case.
jQuery(".delete-listing-btn").on("click", function(e) {
var thisPost = jQuery(e.target).parents(".agent-dashboard-listing-card")
sendRequest('properties-for-sale');
});
const sendRequest = (requestUrl) => {
jQuery.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', msSiteData.nonce);
},
url: `https://mallorca-select.com/wp-json/wp/v2/${requestUrl}/${thisPost.data('id')}`,
type: 'DELETE',
success: function () {
alert(" Listing Deleted Successfully! ");
},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " error);
}
});
};
CodePudding user response:
To do what you require you can use another data
attribute to hold the post type URL route - as you already are for the id
:
jQuery($ => {
$(".delete-listing-btn").on("click", e => {
let $button = $(e.target);
let $thisPost = $button.parents(".agent-dashboard-listing-card");
let url = `https://example.com/wp-json/wp/v2/${$button.data('post-type')}/${$button.data('id')}`;
console.log(url);
// your AJAX request here...
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button data-post-type="post-type-1" data-id="1">Post Type 1</button>
<button data-post-type="post-type-2" data-id="2">Post Type 2</button>
<button data-post-type="post-type-3" data-id="3">Post Type 3</button>
<button data-post-type="post-type-4" data-id="4">Post Type 4</button>