Wordpress Ajax - Js error 400(bad request) - php

It's getting the link to the word press ajax file but giving me a bad request error.
The exact error im getting is POST http://[Website URL]/wp-admin/admin-ajax.php 400 (Bad Request)
Functions.php file
function as_custom_ajax_localizing() {
wp_enqueue_script( 'custom.js', get_template_directory_uri() . '/guest-list/custom.js', array( 'jquery' ), '1.0.0', true );
wp_localize_script( 'custom.js', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'as_custom_ajax_localizing' );
Custom php file
add_action( 'wp_ajax_my_delete_post', 'as_delete_guest' );
function as_delete_guest(){
$permission = check_ajax_referer( 'as_delete_guest_nonce', 'nonce', false );
if( $permission == false ) {
echo 'error';
} else {
wp_delete_post( $_REQUEST['id'] );
echo 'success';
}
die();
}
Custom Js file
$( document ).ready(function() {
$( ".remove_guest" ).click(function() {
var guestRowId = $(this).attr('id');
alert( "This id is " + guestRowId + " and has been clicked");
var nonce = $(this).data('nonce');
$.ajax({
type: 'post',
url: MyAjax.ajaxurl,
data: {
action: 'my_delete_post',
nonce: nonce,
id: guestRowId
},
success: function( result ) {
if( result == 'success' ) {
alert("Success");
}
else{
alert("problem");
}
}
})
return false;
});
});

Related

How to get ACF Field Value with AJAX

little help please, it is WP site,
I have hidden section on page, and when user scroll to it popup shows asking for password, and when user enter password I must compare it with password from ACF field.
I tried several examples getting this done but i cant get anything... I could not find any clear examples of that on stackowerflow, or step by step examples, there are few of them that are not clear to me, I am kinda beginer
EDIT:
function.php
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/global.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
add_action('wp_ajax_nopriv_get_acf_field_ajax', 'my_action');
add_action('wp_ajax_get_acf_field_ajax', 'my_action');
function my_action() {
$result = get_field('password', 'option');
echo json_encode($result);
// wp_send_json($result);
}
global.js
$.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: { action: 'my_action' },
success: function (data) {
console.log(data);
}
});
i got POST http://my-local-website.com/wp-admin/admin-ajax.php error 400 bad request
You have to register and localize a script file in your theme function.php.
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
After localizing your JS file, you can use my_ajax_object object in your JS file:
var form_data = new FormData();
form_data.append('action', 'get_acf_field_ajax');
form_data.append('pass', password);
form_data.append('user_id', 141);
jQuery.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: form_data,
success: function(response){
console.log(response.success);
}
});
then you have to write your ajax callback function.
<?php
add_action('wp_ajax_nopriv_get_acf_field_ajax', 'my_action');
add_action('wp_ajax_get_acf_field_ajax', 'my_action');
function my_action() {
$response = array();
$user_id = $_POST['user_id'];
$user_pass = $_POST['pass'];
$acf_pass = get_field('acf_pass', 'user_'. $user_id );
if($user_pass == $acf_pass ){
$response['success'] = true;
}else{
$response['success'] = false;
}
wp_send_json($response);
}
?>
try out this rough code and modify as per your need.
This is how I manage to do it:
JS File:
$('.pwd').on('click', function () {
var pwd = prompt('Please enter your password:', '');
if (pwd != null && pwd != '') {
var password = pwd;
$.ajax({
url: example_ajax_obj.ajaxurl,
data: {
'action': 'example_ajax_request',
'password': password,
},
success: function (data) {
console.log(data);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
}
return false;
});
function example_ajax_enqueue() {
// Enqueue javascript on the frontend.
wp_enqueue_script(
'example-ajax-script',
get_template_directory_uri() . '/js/global.js',
array( 'jquery' )
);
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script(
'example-ajax-script',
'example_ajax_obj',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action( 'wp_enqueue_scripts', 'example_ajax_enqueue' );
function example_ajax_request() {
$acf_pass = get_field('password', 'option');
// The $_REQUEST contains all the data sent via ajax
if ( isset( $_REQUEST ) ) {
$password = $_REQUEST['password'];
if ( $password == $acf_pass ) {
$password = 'YESSSSSSS';
}else{
$password = 'NOOOOOO';
}
echo $password;
}
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

WordPress ajax request not getting value by PHP

I sent an ajax request by a button, ajax requests work perfectly also responding. I checked the browser Network it is fine. My problem is I am not getting value by PHP request. Here is my code given below:
function my_enqueue(){
wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ) . '/assets/js/awqvCustom.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
/* Custom Ajax */
function data_custom_ajax(){
if ( isset($_POST)) {
$id = $_POST['id'];
echo $id;
}
die();
}
add_action('wp_ajax_nopriv_data_custom_ajax', 'data_custom_ajax');
add_action('wp_ajax_data_custom_ajax', 'data_custom_ajax');
/* Modal Markup*/
function modalBody(){?>
<div class="my-modal">
<div id="ajax_result"></div> //getting ajax success value here
<?php
$getId = (isset($_POST['id']) ? $_POST['id'] : '');
echo $getId; //nothing get
?>
</div>
<?php }
add_action('get_footer', 'modalBody');
jQuery ajax code:
jQuery(document).ready(function () {
'use strict';
jQuery(".btn-container").on('click','.open-modal', function(e){
e.preventDefault();
var id = jQuery(this).data('id');
jQuery.ajax({
type: "POST",
url: my_ajax_object.ajax_url,
dataType:"json",
data: {
action: 'data_custom_ajax',
id: id,
},
cache: false,
success: function(data){
if(data !=''){
jQuery('#ajax_result').html(data);
var modal = jQuery(".my-modal").wgModal();
modal.openModal();
}
}
});
});
I checked with the debugger. The ajax variables seem to be sent

AJAX Wordpress ACF update with button click id

I using ACF wordpress to update acf field for user to populate with button id click.
I am getting Error as admin-ajax.php with 400
Error POST https://domainname/wp-admin/admin-ajax.php 400 ()
Wordpress code on template
<button class="get_project" id="1479" name="urbtnid" data-postid="147">Get project</button>
<button class="get_userbtn" value="<?php echo get_current_user_id() ?>" id="get_userbtn" ><?php echo get_current_user_id() ?></button>
**
JQUery AJAX Code
**
jQuery(function($){
$('.get_project').click(function() {
var stdid = jQuery('#get_userbtn').attr('value');
var stdbtnid = this.id;
jQuery.ajax({
url: my_ajax_object.ajax_url,
type : 'post',
data: dataString,
success : function( response ) {
console.log(response);
}
});
})
});
**
Function.php code
**
function my_enqueue_ajax_save() {
wp_register_script( 'ajax-script', get_template_directory_uri() . '/pradeep-js-css/my-ajax-id-save-script.js', array('jquery') , false, true );
wp_enqueue_script( 'ajax-script' );
wp_localize_script( 'ajax-script', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_ajax_save' );
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action(){
$postid = $_POST['stdid1'];;
$fieldname = 'last_question_viewed';
$fieldvalue = $_POST['stdbtnid1'];
update_post_meta($postid, $fieldname, $fieldvalue);
echo $postid;
wp_die($fieldname = '', $fieldvalue = '', $postid = '');
}
Updated jquery with action
jQuery(function($){
var stdid = jQuery('#get_userbtn').attr('value');
var stdbtnid = this.id;
var dataString = 'stdid1=' + stdid + '&stdbtnid1=' + stdbtnid;
$('.get_project').click(function() {
var data = {
action: "my_action",
stdid: stdid,
stdbtnid1: stdbtnid
};
jQuery.ajax({
url: my_ajax_object.ajax_url,
type : 'post',
data: data,
success : function( response ) {
console.log(response);
}
});
})
});

Load wordpress templates with ajax

I want to load my templates with ajax, but I am having struggles (doesn't work at all), mostly with the PHP I guess. I am trying to get whatever template is the correct one using the ID to get the template slug, but doesn't seem to be working.
Here is my code so far:
function theme_js() {
wp_enqueue_script( 'ajaxstuff', get_template_directory_uri() . '/js/ajax.js', array('jquery'), '', true );
wp_localize_script( 'ajaxstuff', 'ajaxify', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
}
add_action( 'wp_enqueue_scripts', 'theme_js' );
add_action( 'wp_ajax_nopriv_ajax_submit', 'my_ajax_submit' );
add_action( 'wp_ajax_ajax_submit', 'my_ajax_submit' );
function my_ajax_submit() {
$pageUrl = $_REQUEST['URL'];
$postid = url_to_postid( $pageUrl );
$post = get_post($postid);
$pageSlug = get_page_template_slug($postid);
if ($post) {
setup_postdata($post);
get_template_part( $pageSlug );
}
exit();
}
And my JS:
(function($){
$('body').on('click', 'a', function(e) {
e.preventDefault();
var URL = $(this).attr('href');
animationFunction();
var ajaxPromise = $.ajax({
url: ajaxify.ajaxurl,
type: "post",
data: {
action: 'my_ajax_submit',
url: URL
},
dataType: "html"
});
var animationPromise = animationFunction();
$.when(ajaxPromise, animationPromise).done(function(data) {
$('#page-wrap').html(data[0]);
TweenMax.to('.page', 0.35, { alpha: 1 });
});
});
function animationFunction() {
var deferred = $.Deferred();
TweenMax.to('.page', 0.35, { alpha: 0, onComplete: deferred.resolve });
return deferred.promise();
}
})(jQuery);
$pageUrl = $_REQUEST['URL'];
$_REQUEST contains an associative array and array indexes are case sensitive, so:
$pageUrl = $_REQUEST['url'];

wordpress ajax call keep on running after calling once

I made a wordpress ajax call code in which when i click on a button the the function runs properly and returns the value first time as it should but after that the ajax call to admin-ajax.php keepon running as i can see from developer tools . My code is
add_action( 'wp_ajax_arete_bp_endorse', 'arete_bp_endorse_ajax' );
add_action( 'wp_ajax_nopriv_arete_bp_endorse', 'arete_bp_endorse_ajax' );
function arete_bp_endorse_ajax(){
global $wpdb;
$result['type'] = "works";
echo $result;
wp_die();
}
function my_script_enqueuer() {
wp_register_script( "my_voter_script", WP_PLUGIN_URL.'/example/js/example.js', array('jquery') );
wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'my_voter_script' );
}
the example.js file code
jQuery(document).on("click",".endorse-bt", function (event){
event.preventDefault();
var type= jQuery(this).attr("data");
var option= jQuery(this).parents("li").attr("data-endorsed-item-name");
var profile_id=jQuery(this).parents("li").attr("data-prf-id");
var login_id=jQuery(this).parents("li").attr("data-lg-id");
jQuery.ajax({
dataType : "json",
url : myAjax.ajaxurl,
type: 'POST',
data:{action: "arete_bp_endorse", type : type, option: option, profile_id: profile_id, login_id: login_id},
success: function( response ){
//Do something with the result from server
alert(response.type);
}
});
});

Categories