"Bad Request" 400 server response for AJAX request - javascript

All of the usual suspects have been tried to no avail, including setting: ContentType: and dataType:. jQuery has defaults for both, if not specified. Tried serializing the json using JSON.stringify(data) - all combinations of the above don't change the server response. Can't see what I'm missing here that's causing the problem.
Here's the javascript in question:
jQuery(document).ready(function() {
jQuery('.delete_listing').on('click', (function(e) {
var post_type = jQuery(this).data( 'type' ); // Get post type via the 'data-type' attribute of the button.
e.preventDefault();
if (confirm('You want to delete this listing?')) {
jQuery.ajax({
url: fpf_ajax_delete_listing.ajax_url, // 'fpf_ajax_delete_listing' is from wp_localize_script() call
type: 'post',
data: {
action: 'fpf_ajax_delete_listing_process', // part of add_action() call
nonce: fpf_ajax_delete_listing.fpf_delete_listing_nonce, // from wp_localize_script() call.
post_type : post_type
},
success : function( response ) {
console.log(response);
},
error : function( response) {
alert('Error retrieving the information: ' + response.status + ' ' + response.statusText);
console.log(response);
}
});
// clear edit page, msg delete successful, redirect to seller account dashboard
jQuery(function() {
jQuery(".form-group").remove();
jQuery("p").remove();
jQuery("#remove-listing").remove();
jQuery("hr").replaceWith('<h4 style="color:green;"><em>Listing successfully deleted.</em></h4>');
// return to seller dashboard
}); // clear & redirect
} else {
// Do nothing!
}
}));
});
And here's the PHP from the plugin:
function fpf_ajax_delete_listing_shortcode() {
return '<button class="delete_listing" data-type="post" type="button" style="background:red; border-radius:5px; border-width:1px; color:white;">Delete Listing</button>';
}
add_shortcode('ajax_delete_listing', 'fpf_ajax_delete_listing_shortcode');
add_action('wp_enqueue_scripts', 'fpf_enqueue_scripts');
function fpf_enqueue_scripts() {
wp_enqueue_script( 'fpf-delete-listing', plugin_dir_url( __FILE__ ). 'ajax-delete-listing-code.js', array('jquery') );
wp_localize_script( 'fpf-delete-listing', 'fpf_ajax_delete_listing', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'fpf_delete_listing_nonce' => wp_create_nonce('fpf-delete-listing-nonce')
));
}
add_action( 'wp_ajax_fpf_ajax_delete_listing', 'fpf_ajax_delete_listing', 20 ); // logged in users only.
function fpf_ajax_delete_listing() {
check_ajax_referer( 'fpf-delete-listing-nonce', 'nonce' ); // dies if nonce is not correct.
$post_id = get_the_ID();
update_post_meta($post_id, 'wpcf-listing-status', 'inactive');
}
return;

Related

JavaScript with Ajax call to the WordPress API

I'm making a Wordpress plugin named "customposttype" that makes a custom post type with 3 custom fields. The plugin also must do an Ajax call to the WordPress API and gets all the data from those posts in JSON format, to show them in a specific template called "shoplist.php".
My CPT is called "tienda", it has this url for the REST API: ...wp-json/wp/v2/tiendas.
I'm sure that I have several errors because it's my first time using an API and I'm very bad at Javascript.
I'm stuck just right here, I don't know how to continue developing it.
JS shows "Hello world!" at the console, but nothing else.
PHP
add_action("wp_ajax_nopriv_get_shop_data", "get_shop_data");
add_action("wp_ajax_get_shop_data", "get_shop_data");
function get_shop_data() {
$api_url = "https://pezquefuma.es/wp-json/wp/v2/tiendas";
$request = wp_remote_get($api_url);
$body = wp_remote_retrieve_body($request);
$output = json_encode($body, true);
echo $output;
die();
}
function my_enqueue() {
if ( get_page_template_slug() == 'shoplist.php' ) {
wp_enqueue_script( 'ajax-script', plugins_url('customposttype/js/filename.js'), array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('my-nonce')
)
);
}
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
JS
jQuery( document ).ready(function() {
console.log("Hello world!");
jQuery.ajax({
type : "GET",
dataType : "JSON",
url : my_ajax_object.ajax_url,
data : {
action: "get_shop_data",
},
error: function(response, error) {
console.log("wrong");
},
success : function(response) {
if(response.type === "success") {
console.log("Success");
}
}
});
});
There are two ways to check response data.
one is to use browser's network devtool and another is to use console.log
success : function(response) {
console.log(response);
}

Can't Output Anything from WordPress AJAX, no Errors

I have an issue with Ajax in WordPress, I viewed 1000 posts about AJAX for a WordPress, but nothing. Everything seems ok.
I have a button with data-id attribute for every post on my index page, inside data-id I have its post id.
So idea is simple when someone click on this button I want to create a div with text, which will be post id. But I get nothing, I haven't any error, in my console everything is ok, but div is not created.
My enqueue scripts:
function _themename_assets() {
wp_enqueue_script( '_themename-dummy-scripts', get_template_directory_uri() . '/dist/assets/js/ajax.js', array('jquery'), '1.0.0', true );
wp_localize_script('_themename-dummy-scripts', 'viasun_dummy_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
));
}
add_action('wp_enqueue_scripts', '_themename_assets');
My JS:
$('.c-post__button a').on( 'click', function(e){
e.preventDefault();
var button = $(this);
var id = button.data('id');
var data = {
id: id,
action: "viasun_dummy_ajax_data_action"
};
$.ajax({
url: viasun_dummy_ajax.ajax_url,
data: data,
type: "POST",
beforeSend: function( ) {
console.log("sending");
},
success: function(message) {
if( data ) {
$("body").append(data);
console.log(data);
}
},
error: function() {
console.log("error");
}
} );
});
My action for ajax:
function viasun_dummy_ajax_data_action(){
$id = $_POST['id'];
echo '<div class="id-container">' . $id . '</div>';
wp_die();
}
add_action( 'wp_ajax_viasun_dummy_ajax_data_action', 'viasun_dummy_ajax_data_action' );
add_action( 'wp_ajax_nopriv_viasun_dummy_ajax_data_action', 'viasun_dummy_ajax_data_action' );
In my console from js I get:
Object { id: 15, action: "viasun_dummy_ajax_data_action" }
And XHR in console says 200 OK.
What am I doing wrong? Can you help me, please?

Wordpress ajax call in an admin menu page

I'm trying to use the data of an ajax call in my custom wordpress admin menu page.
The wp_localize_script is working fine:
wp_enqueue_script( 'ajax-function', plugin_dir_url( __FILE__ ) . 'JavaScript/ajax-function.js', array( 'jquery' ), $this->version,false );
wp_localize_script('ajax-function', 'WP_MY_AJAX',
array(
'security' => wp_create_nonce('wp-my-nonce'),
'success' => 'this is a success',
'error' => 'an error occurred'
)
);
If I click the button, my ajax fires and it has a status of 200.
jQuery(document).ready(function() {
let message = jQuery('.table-message');
jQuery('#ajax-test').on('click', function () {
let data = 111;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'get_edit_id',
security: WP_MY_AJAX.security,
edit_id: data
},
success: function ( response ) {
//Do something
},
error: function ( error ) {
jQuery('.error').remove();
message.after('<div class="error"><p>' + WP_ESCORT_AJAX.error + '</p></div>');
}
});
});
I end up in this function, which is located in my main plugin file.
function my_escort_get_edit_id() {
check_ajax_referer('wp-escort-nonce', 'security');
echo $_POST['edit_id']
die();
}
add_action('wp_ajax_get_edit_id', 'my_escort_get_edit_id');
add_action('wp_ajax_nopriv_get_edit_id', 'my_escort_get_edit_id');
However my goal is to work with the $_POST['edit_id'] in my admin menu page function:
function my_custom_admin_menu() {
add_menu_page(
__( 'My Menu', 'my-menu' ),
__( 'My Menu', 'my-menu' ),
'edit_posts',
'my-menu-slug',
'my_admin_page_function',
'dashicons-universal-access',
3 ) ;
}
add_action( 'admin_menu', 'my_custom_admin_menu' );
function my_admin_page_function() {
require_once __DIR__ . '/View/Admin/Partials/cover-menu-models.php';
requireModel('all');
$controller = new ModelController();
$modelQuery = $controller->modelQuery('all');
echo $controller->renderModelDataTables($modelQuery, 'all');
//I need the id here
}
How can I achive this?

Pass JavaScript variable to PHP function within Ajax call?

I'm trying to create an ajax search form that gets WordPress posts if the search term is found within the post title. This is my PHP function:
function get_records_ajax($query) {
$args = array(
'post_type' => array('record'),
'post_status' => array('publish'),
'posts_per_page' => 999,
'nopaging' => true,
'meta_query' => array(
'key' => 'title',
'value' => $query,
'compare' => 'IN',
)
);
$ajaxposts = get_posts( $args );
echo json_encode( $ajaxposts );
exit;
}
And this is my jQuery function:
jQuery('.rrm_search_form').on('submit', function(e){
e.preventDefault();
let query = jQuery(this).find('.rrm_search_input').val();
console.log('search submitted for ' + query);
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "json",
data: { action : `get_records_ajax(${query})` },
success: function( response ) {
jQuery.each( response, function( key, value ) {
console.log( key, value );
});
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
}
});
});
I've tried lots of different syntax to try and pass the variable within the data action of my ajax call but nothing's working. Any ideas how I might be able to do this?
I assume your ajax URL is fine and loading in the website.
Now all you have to modify your JS scripts and need to add hooks in PHP section. First in your JS script modify the data: line as follows:
data: { action : 'get_records_ajax', query: query },
Also You can add security check if you want. but leave it now.
Secondly, in your PHP file add the following code..
add_action( "wp_ajax_nopriv_get_records_ajax", 'get_records_ajax' );
add_action( "wp_ajax_get_records_ajax", 'get_records_ajax' );
and then in your get_records_ajax receive the query value
function get_records_ajax(){
$query = sanitize_text_field($_POST['query']);
//then your rest code
}
It will return all the post. Now you need to adjust your JS code in the success block :
success: function( response ) {
console.log(response)
//adjust here with your HTML dom elements
}

AJAX commenting in WordPress

I'm trying to get AJAX commenting working in WordPress. So far I have written a PHP handler and a script.
My script (modified from here):
jQuery(document).ready(function($){
var commentform = $('#commentform');
commentform.prepend('<div id="comment-status"></div>');
var statusdiv = $('#comment-status');
commentform.submit(function(){
//serialize and store form data in a variable
var data=commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl=commentform.attr('action');
//Post Form with data
$.ajax({
type: 'POST',
url: formurl,
dataType: 'JSON',
data: data,
error: function(XMLHttpRequest, errorThrown)
{
statusdiv.html('<p class="ajax-error" >Oops, an error occured</p>');
},
success: function(data)
{
statusdiv.html(data);
$('#commentform #comment').val('');
}
});
return false;
});
});
My PHP handler:
function ajaxify_comments( $comment_ID, $comment_status ) {
$comment = get_comment( $comment_ID );
$response = $comment->comment_content;
echo json_encode( $response );
die();
}
add_action( 'comment_post', 'ajaxify_comments', 20, 2 );
My PHP handler, ajaxify_comments(), is hooked to comment_post which fires immediately after the comment is saved to the database. The function gets the comment text and returns a response (the comment text) to my AJAX script. If everything is successful, the comment text is displayed on screen. If unsuccessful, an error message is displayed.
My problem
If I submit a comment, the comment is saved to the database and the comment text is displayed on screen. This bit works! My problem is if I make a second comment without refreshing the page - I always get "Oops, an error occurred". What am I doing wrong?
Update
After #adeneo's suggestion to use the WordPress built in AJAX hooks I have come up with a new script and PHP handler...
Script:
jQuery(document).ready(function($) {
var path = ac.path;
var security = ac.security;
var ajax_url = ac.ajax_url;
var commentform = $('#commentform');
commentform.prepend('<div id="comment-status"></div>');
var statusdiv = $('#comment-status');
commentform.submit(function(){
$.ajax({
type: 'POST',
url: ajax_url,
dataType: 'JSON',
data: {
'action': 'ac',
'security': security
},
success:function(data) {
statusdiv.html(data);
$('#commentform #comment').val('');
},
error: function(data){
statusdiv.html('<p class="ajax-error">Oops, an AJAX error occured</p>');
}
});
return false;
});
});
PHP handler
function ajaxify_comments() {
check_ajax_referer( 'ajax_ac_nonce', 'security' );
$response = 'blah';
echo json_encode( $response );
die();
}
add_action( 'wp_ajax_ac', 'ajaxify_comments' );
For completeness it is worth letting you know that I also have:
wp_enqueue_script( 'ac-script', plugins_url( '/js/script.js', __FILE__ ), array( 'jquery' ), 1.0, true );
$path = get_bloginfo( 'stylesheet_directory' );
// set the nonce security check
$ajax_nonce = wp_create_nonce( 'ajax_ac_nonce' );
wp_localize_script(
'ac-script',
'ac',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'path' => $path,
'security' => $ajax_nonce,
)
);
My question now becomes: How do I make the submitted comment data available to my PHP handler? I guessing I'll need to manually save the comment data to the database? I need this data available in my PHP function first but not sure how to do that?

Categories

Resources