Wordpress admin-ajax.php error 400 bad request - php

hello im doing save for later feature in my website
but i get admin-ajax bad request when i click the button
functions.php
function zumra_scripts() {
wp_register_script( 'remove-prodduct-from-list', get_template_directory_uri() . '/js/remove-product.js', array('jquery'), false, true );
wp_localize_script( 'remove-prodduct-from-list', 'sfl_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )) );
if ( is_page('savelist') ) {
wp_enqueue_script( 'remove-prodduct-from-list' );
}
}
add_action( 'wp_enqueue_scripts', 'zumra_scripts' );
save-for-later.php
<?php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
$user = $_POST['user'];
$post_id = $_POST['post_id'];
$response = $_POST['saveForLater'];
$response .= ''. __( 'Browse Savelist', 'zumra' ) .'';
add_user_meta( $user, 'product_id', $post_id);
echo $response;
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_remove_product_from_list', 'remove_product_from_list' );
function remove_product_from_list() {
$user = intval( $_POST['user'] );
$product = intval( $_POST['product'] );
delete_user_meta( $user, 'product_id', $product);
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_move_to_cart', 'move_to_cart' );
function move_to_cart() {
$user = intval( $_POST['user'] );
$product = intval( $_POST['product'] );
delete_user_meta( $user, 'product_id', $product);
// do_action( 'woocommerce_ajax_added_to_cart', $product );
// wc_add_to_cart_message( $product );
wp_die(); // this is required to terminate immediately and return a proper response
}
save-for-later.js
jQuery(document).ready(function($) {
$('.ajax-form').on('submit',function(e){
e.preventDefault();
var data = {
'action': 'my_action',
'saveForLater': sfl_ajax.response,
'user': sfl_ajax.user,
'post_id': sfl_ajax.post_id,
'product_id': sfl_ajax.user_product,
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(sfl_ajax.ajaxurl, data, function(response) {
$('.save-for-later').html(response);
});
});
});
i don't know what im doing wrong
i get error admin-ajax.php 400 every time i click add to save for later button

Try with below code. I am assuming that you have include this file in the functions.php of your active theme.
Or
You can add this code in your functionctions.php directly.
As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:
wp_ajax_(action): This is fired if the ajax call is made from inside
the admin panel.
wp_ajax_nopriv_(action): This is fired if the ajax
call is made from the front end of the website.
add_action( 'wp_ajax_my_action', 'my_action' );
add_action("wp_ajax_nopriv_my_action","remove_product_from_list");
function my_action() {
$user = $_POST['user'];
$post_id = $_POST['post_id'];
$response = $_POST['saveForLater'];
$response .= ''. __( 'Browse Savelist', 'zumra' ) .'';
add_user_meta( $user, 'product_id', $post_id);
echo $response;
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_remove_product_from_list', 'remove_product_from_list' );
add_action("wp_ajax_nopriv_remove_product_from_list","remove_product_from_list");
function remove_product_from_list() {
$user = intval( $_POST['user'] );
$product = intval( $_POST['product'] );
delete_user_meta( $user, 'product_id', $product);
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_move_to_cart', 'move_to_cart' );
add_action("wp_ajax_nopriv_move_to_cart","GetEditForm");
function move_to_cart() {
$user = intval( $_POST['user'] );
$product = intval( $_POST['product'] );
delete_user_meta( $user, 'product_id', $product);
// do_action( 'woocommerce_ajax_added_to_cart', $product );
// wc_add_to_cart_message( $product );
wp_die(); // this is required to terminate immediately and return a proper response
}

Related

How do I add cookie value in order metadata in WooCommerce?

I want the value of cookie my_cookie in order metadata.
add_action('init','thankyou_grab_cookie_as_meta_data', 10, 1 );
function thankyou_grab_cookie_as_meta_data( $order_id ){
if( ! $order_id ){
return;
}
if(isset($_COOKIE["my_cookie"]) && ! get_post_meta( $order_id, 'some default value', true ) ){
update_post_meta( $order_id, 'some default value', esc_attr($_COOKIE["my_cookie"]) );
}
}
The metadata shown now in postman
I guess the problem is with the check on ! get_post_meta and then you update_post_meta while it doesn't exists yet. Have update the code below.
add_action('init', 'thankyou_grab_cookie_as_meta_data', 10, 1);
function thankyou_grab_cookie_as_meta_data($order_id) {
if (!$order_id) {
return;
}
if (isset($_COOKIE["my_cookie"])) {
$my_cookie = esc_attr($_COOKIE["my_cookie"]);
if (!get_post_meta($order_id, 'some_meta_key', true)) {
add_post_meta($order_id, 'some_meta_key', $my_cookie);
} else {
update_post_meta($order_id, 'some_meta_key', $my_cookie);
}
}
}
Seems like you are using the WP REST API, maybe you haven't registered the custom field yet. You can use register_rest_field
add_action('rest_api_init', 'custom_register_rest_field');
function custom_register_rest_field() {
register_rest_field(
'post', // post type
'some_meta_key', // meta key
);
}

Get user name inside AJAX success function

I'm trying to display the username when an AJAX request is successful.
The problem that I'm running into is that the name remains blank.
Simplified code (removed if statements, checks, and other unrelated code)
wp_localize_script('follow-me-ajax', 'ajax_setting', array(
'ajax_url' => admin_url('admin-ajax.php'),
'ajax_nonce' => wp_create_nonce('km-ajax-create-nonce'),
'ajax_follow_success' => $this->follow_me_success(),
));
AJAX Call
var user_to_follow = $('.km-author-follow a.km-meta-badge').attr('id');
$.ajax( {
url : ajax_setting.ajax_url,
type : 'post',
data: {
action : 'theme_ajax_follow_me',
security : ajax_setting.ajax_nonce,
'data-follow-user' : user_to_follow,
},
success: function( data ) {
$('.km-follow-me').html( ajax_setting.ajax_follow_success ).hide().fadeIn( 'slow' );
console.log( user_to_follow );
},
} )
Inside the wp ajax function I use this
public function theme_addon_ajax_follow_me() {
...
$target_user = isset( $_POST['data-follow-user'] ) ? $_POST['data-follow-user'] : false;
if( ! empty( $_POST['data-follow-user'] ) ) {
$this->kiwi_follow_user( $current_user, $target_user );
}
wp_die();
}
Up next; this function sends the $target_user ID to km_follow_me_author_name
public function kiwi_follow_user( $current_user = 0, $user_to_follow = 0 ) {
...
$args = array(
'user_id' => $current_user,
'follow_to' => $user_to_follow
);
$response_success = $this->km_follow_me_author_name( $args );
}
Function to grab display name based on AJAX's $_POST['data-follow-user']
public function km_follow_me_author_name( $args = array() ) {
$author_info = get_userdata( $args['follow_to'] );
$author = $author_info->display_name;
return $author;
}
The success message and where it goes wrong. $name remains blank.
public function follow_me_success() {
$name = $this->km_follow_me_author_name();
$content = sprintf( esc_html__( 'You\'re now following %s.', 'theme' ), $name );
return $content;
}
Any help is much appreciated.
First I removed this line from wp_localize_script
'ajax_follow_success' => $this->follow_me_success(),
Then changed the success function from AJAX to:
$('.km-follow-me').html(data).hide().fadeIn( 'slow' );
Then inside public function kiwi_follow_user I used:
if ( ! empty( $response ) && $response !== FALSE ) {
$this->km_follow_me_success( $user_to_follow );
}
And inside the follow_me_success function, I replaced return with echo instead.
public function follow_me_success( $target_user = 0 ) {
$name = $this->km_follow_me_author_name( $target_user );
$content = sprintf( esc_html__( 'You\'re now following %s.', 'theme' ), $name );
echo $content;
}
Minor changes, big difference. :)

Getting applied coupons in cart in woocommerce_init hook

I am trying to get the coupons used in order under woocommerce_init. Tried to view the array $GLBALS and found smth related but don't know how to access them.
function remove_email_for_testcop_coupon($order_id) {
global $woocommerce;
$coupons = $woocommerce->cart->applied_coupons;
var_dump($GLOBALS['GLOBALS']['wp_filter']['init']); //=> here there are found but don't know how to access it normaly => need to reach applied_coupons, just that is generating a dinamic nonce.
remove_action( 'init', array( 'WC_Emails', 'init_transactional_emails' ) );
if (in_array('testcop', $coupons)) {
remove_action( 'init', array( 'WC_Emails', 'init_transactional_emails' ) );
}
}
//add_action('wp', 'remove_email_for_testcop_coupon');
add_action( 'woocommerce_init', 'remove_email_for_testcop_coupon');
Managed to find out how:
function remove_email_for_testcop_coupon($order_id) {
global $wp;
$coupons = array();
$cpage = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($cpage, '/course/') === false) {
$obj = new WC_Session_Handler();
$data = accessProtected($obj, '_data');
$coupons = unserialize($data['applied_coupons']);
if (!empty($coupons)) {
if (in_array('masterkey', $coupons) || in_array('testcop', $coupons)) {
remove_action( 'init', array( 'WC_Emails', 'init_transactional_emails' ) );
}
}
}
}
add_action( 'woocommerce_init', 'remove_email_for_testcop_coupon');

Wordpress Single User Session

I'm using the Current version of Wordpress (4.2.4) and woocommerce (2.3.6).
Problem: Don't let users share their login details to the site.
Old Solution: The Answer to this question has been working until now.
What i need: Can anyone see what's wrong with this code & why it wouldn't work with the new Wordpress update (4.2.4).
Or offer up another solution.
Code from answer by #manoj-dhiman:
how can I prevent multiple login from same user id from different browsers in wordpress?
if( !class_exists( 'WPSingleUserLoggin' ) ) {
class WPSingleUserLoggin
{
private $session_id;
function __construct()
{
if ( ! session_id() )
session_start();
$this->session_id = session_id();
add_action( 'init', array( $this, 'init' ) );
add_action( 'wp_login', array( $this, 'wp_login' ), 10, 2 );
}
function init()
{
if( ! is_user_logged_in() )
return;
$stored_sess_id = get_user_meta( get_current_user_id(), '_wp_single_user_hash', true );
if( $stored_sess_id != $this->session_id )
{
wp_logout();
wp_redirect( wp_login_url() );
exit;
}
}
function wp_login( $user_login, $user )
{
update_user_meta( $user->ID, '_wp_single_user_hash', $this->session_id );
return;
}
}
new WPSingleUserLoggin();
}

Validate custom fields in wordpress post

I have a custom post type speaker and in speaker I have a custom field speaker_organization. How can I validate this and display error in admin notice.
add_action( 'add_meta_boxes', 'speaker_organization_box' );
function speaker_organization_box() {
add_meta_box(
'speaker_organization',
__( 'Organization', 'dbem' ),
'speaker_organization_box_content',
'speaker',
'side',
'high'
);
}
function speaker_organization_box_content( $post ) {
// generate a nonce field
wp_nonce_field( basename( __FILE__ ), 'dbem-speaker-organization-nonce' );
// get previously saved meta values (if any)
$speaker_organization = get_post_meta( $post->ID, 'speaker_organization', true );
echo '<label for="speaker_organization"></label>';
echo '<input type="text" id="speaker_organization" name="speaker_organization" placeholder="Organization Name" value="'.$speaker_organization.'" />';
}
function speaker_organization_box_save( $post_id ) {
$speaker_organization = $_POST['speaker_organization'];
update_post_meta( $post_id, 'speaker_organization', $speaker_organization );
}
add_action( 'save_post', 'speaker_organization_box_save' );
using
add_action( 'admin_notices', 'my_admin_notice' );
or using validate js
add_action('admin_enqueue_scripts', 'add_my_js');
function add_my_js(){
wp_enqueue_script('my_validate', 'path/to/jquery.validate.min.js', array('jquery'));
wp_enqueue_script('my_script_js', 'path/to/my_script.js');
}
jQuery().ready(function() {
jQuery("#post").validate();
});
<input type="text" name="my_custom_text_field" class="required"/>
function wpse_update_post_custom_values($post_id, $post) {
// Do some checking...
if($_POST['subhead'] != 'value i expect') {
// Add an error here
$errors->add('oops', 'There was an error.');
}
return $errors;
}
add_action('save_post','wpse_update_post_custom_values',1,2);
validate js code
using condition + admin notice

Categories