wordpress Ajax call to php function doesn't work - php

I've tried a bunch of different things but I just cannot get AJAX with Wordpress to work. I clearly don't get something but I do not know what it is. Always get a result on admin-ajax.php 0
public function enqueue_scripts() {
wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/jquery-3.3.1-public.js', array( 'jquery' ), "3.3.1", false );
wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ). 'js/wp-public.js', __FILE__, array() , $this->version, true);
wp_localize_script( 'ajax-script', 'ajax_object',
array(
'ajax_url' => admin_url( 'admin-ajax.php')
)
);
}
wp-public.js
$(document).ready(function()
{
$(".like-btn, .dislike-btn").click(function()
{
var id = this.id; // Getting Button id
var split_id = id.split("_");
var text = split_id[0];
var postid = split_id[1]; // postid
// Finding click type
var type = 0;
if(text == "like-btn") {
type = 1;
}else {
type = 0;
}
// AJAX Request
$.ajax(
{
url: ajax_object.ajax_url,
type: 'post',
data: {
'action': 'my_action',
postid: postid,
type: type
},
dataType: 'json',
success: function(data) {
$("#likes_"+postid).text(data.likes); // setting likes
$("#unlikes_"+postid).text(data.unlikes); // setting unlikes
$("#msg_"+postid).text(data.msg); // setting messages
if (data.likes || data.unlikes > "") {
if(type == 1) {
$("#like-btn_"+postid).css("color", "#0757fe");
$("#dislike-btn_"+postid).css("color", "#8e8e8e");
}
if(type == 0) {
$("#dislike-btn_"+postid).css("color", "#f1476e");
$("#like-btn_"+postid).css("color", "#8e8e8e");
}
}
}
}
);
}
);
}
);
included class
class Wp_Ahb_Content {
public function __construct( ) {
add_action('wp_ajax_my_action','my_action');
add_action('wp_ajax_nopriv_my_action','my_action');
}
function my_action() {
global $wpdb;
$whatever = $_POST['postid'] ;
echo "postid".$whatever;
}
Variables were sent successfully without reply
Screenshots
[ajax response][1]
[ajax_object][2]
[1]: https://i.stack.imgur.com/KlmJ7.jpg
[2]: https://i.stack.imgur.com/TO5i9.jpg

My_action function is not running
JUST Delete add_action from __construct () and add them to loader
add_action ('wp_ajax_my_action', 'my_action');
add_action ('wp_ajax_nopriv_my_action', 'my_action');
And I became as follows: ON private function define_public_hooks()
$this-> loader-> add_action ("wp_ajax_my_action", $ plugin_public, "ajax_object");
 
$this-> loader-> add_action ("wp_ajax_nopriv_my_action", $ plugin_public, "ajax_object");
It became operational
I just wanted to clarify, because I found a lot of questions
regarding the Wordpress Plugin Boilerplate

Related

Woocommerce WC_Form_Handler not found

I'm newly using classes in my Plugin. Before I've used classes, my Ajax add to cart function worked fine.
Now I'm getting this error:
Uncaught Error: Class 'system\core\WC_Form_Handler' not found
("system\core" is the namespace of my file)
Before I am calling Wc_Form_Handler::add_to_cart_action(); I'm checking if this specific class exists. So if the class wouldn't exist, the class wouldn't be called later...)
I've also taken a look into get_declared_classes(); to make sure that my classes are called after the Wc_Form_Handler.
Does someone have any idea how I can deal with that problem?
namespace system\core;
class Woocommerce{
public function __construct() {
add_action( 'wp_footer', array( __CLASS__, 'ace_product_page_ajax_add_to_cart_js' ) );
add_action( 'wc_ajax_ace_add_to_cart', array( __CLASS__, 'ace_ajax_add_to_cart_handler' ) );
add_action( 'wc_ajax_nopriv_ace_add_to_cart', array( __CLASS__, 'ace_ajax_add_to_cart_handler' ) );
add_action('init', array( __CLASS__, 'remove_add_cart_handler' ),10);
}
* JS for AJAX Add to Cart handling
*/
public static function ace_product_page_ajax_add_to_cart_js() {
?><script type="text/javascript" charset="UTF-8">
jQuery(function($) {
$('form.cart').on('submit', function(e) {
e.preventDefault();
var form = $(this);
form.block({ message: null, overlayCSS: { background: '#fff', opacity: 0.6, "border-radius": "30px", } });
var formData = new FormData(form[0]);
formData.append('add-to-cart', form.find('[name=add-to-cart]').val() );
// Ajax action.
$.ajax({
url: wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'ace_add_to_cart' ),
data: formData,
type: 'POST',
processData: false,
contentType: false,
complete: function( response ) {
response = response.responseJSON;
if ( ! response ) {
return;
}
if ( response.error && response.product_url ) {
window.location = response.product_url;
return;
}
// Redirect to cart option
if ( wc_add_to_cart_params.cart_redirect_after_add === 'yes' ) {
window.location = wc_add_to_cart_params.cart_url;
return;
}
var $thisbutton = form.find('.single_add_to_cart_button'); //
// var $thisbutton = null; // uncomment this if you don't want the 'View cart' button
// Trigger event so themes can refresh other areas.
$( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash, $thisbutton ] );
// Remove existing notices
$( '.woocommerce-error, .woocommerce-message, .woocommerce-info' ).remove();
// Add new notices
form.closest('.product').before(response.fragments.notices_html)
form.unblock();
}
});
});
});
</script><?php
}
/**
* Add to cart handler.
*/
public static function ace_ajax_add_to_cart_handler() {
if (class_exists('WC_Form_Handler')){
WC_Form_Handler::add_to_cart_action();
WC_AJAX::get_refreshed_fragments();
}
}
public static function remove_add_cart_handler() {
remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 );
add_filter( 'wc_add_to_cart_message_html', '__return_false' );
}
}
(edit)
Because the class gets loaded I think that this isn't the problem but could my autoloader be the problem?
spl_autoload_register(function ($class_name) {
$location = __DIR__ . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class_name) . '.php';
if (file_exists($location)) {
try {
require_once $location;
return;
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
});
Alright, I got it! You need to define the WC-Form_Handler class as global.
public static function ace_ajax_add_to_cart_handler() {
if (class_exists('WC_Form_Handler')){
\WC_Form_Handler::add_to_cart_action();
\WC_AJAX::get_refreshed_fragments();
}
}

Problem Setting Up AJAX Request in Wordpress (with JQuery)

I am getting an error of "500 (Internal Server Error). I have gone through a lot of the solutions here and they don't seem to change my outcome and I'm not sure why. I am still learning Wordpress and Ajax so any help is appreciated!
My functions.php:
<?php
// register and enqueue custom js scripts
add_action('wp_enqueue_scripts', 'hyix_enqueue_custom_js');
function hyix_enqueue_custom_js() {
//enqueue zip-search-popup.js
wp_enqueue_script('zip-search-popup', get_stylesheet_directory_uri().'/js/zip-search-popup.js', array('jquery'), false, true);
wp_localize_script('zip-search-popup', 'from_php', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
//hook zip-search function into ajax
add_action( 'wp_ajax_zip_search', 'zip_search' );
//same hook for users not logged in
add_action( 'wp_ajax_nopriv_zip_search', 'zip_search' );
//query for pulling in shipping data
function zip_search() {
$submittedZip = $_REQUEST['submittedZip'];
global $wpdb;
// The SQL query
$response = $wpdb-> get_results("SELECT {$wpdb->prefix}woocommerce_shipping_zones.zone_name ".
"FROM {$wpdb->prefix}woocommerce_shipping_zone_locations ".
"INNER JOIN {$wpdb->prefix}woocommerce_shipping_zones ".
"ON {$wpdb->prefix}woocommerce_shipping_zone_locations.zone_id = {$wpdb->prefix}woocommerce_shipping_zones.zone_id ".
"WHERE location_code = '$submittedZip' ");
$response = array(
'request' => $_REQUEST,
'zip' => $submittedZip,
'test' => 'is ok',
);
wp_send_json( $response );
// echo $response;
die();
}
My jQuery file - zip-search-popup.js:
(function($) {
$(document).ready(function() {
$('.zip-bar-button').click(function(event) {
event.preventDefault();
submittedZip = $("#zipcode-bar-input").val();
console.log(submittedZip);
$.ajax({
url: from_php.ajax_url,
type: "POST",
dataType: "json",
data: {
action : 'zip_search',
submittedZip : submittedZip,
},
success: function (response) {
console.log("this is the response: " + response);
alert("working");
},
})
})
})
})(jQuery);
This is working code for you you need to add this code in your child-theme functions.php
I have made few changes to the code the way you wp_enqueue_scripts in wordpress.
child-theme (functions.php)
function my_custom_scripts() {
$myvars = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ) //admin ajax
);
wp_enqueue_script( 'my-ajax-request', get_stylesheet_directory_uri() . '/js/zip-search-popup.js', array( 'jquery' ),'',true );
wp_localize_script( 'my-ajax-request', 'MyAjax', $myvars );
}
add_action( 'wp_enqueue_scripts', 'my_custom_scripts' );
//hook zip-search function into ajax
add_action( 'wp_ajax_zip_search', 'zip_search' );
//same hook for users not logged in
add_action( 'wp_ajax_nopriv_zip_search', 'zip_search' );
//query for pulling in shipping data
function zip_search() {
$submittedZip = $_REQUEST['submittedZip'];
global $wpdb;
//The SQL query
$response = $wpdb-> get_results("SELECT {$wpdb->prefix}woocommerce_shipping_zones.zone_name ".
"FROM {$wpdb->prefix}woocommerce_shipping_zone_locations ".
"INNER JOIN {$wpdb->prefix}woocommerce_shipping_zones ".
"ON {$wpdb->prefix}woocommerce_shipping_zone_locations.zone_id = {$wpdb->prefix}woocommerce_shipping_zones.zone_id ".
"WHERE location_code = '$submittedZip' ");
$response = array(
'request' => $_REQUEST,
'zip' => $submittedZip,
'test' => 'is ok',
);
wp_send_json( $response );
}
child theme (js file - jQuery code) zip-search-popup.js
$(document).ready(function () {
$('.zip-bar-button').click(function (event) {
event.preventDefault();
submittedZip = $("#zipcode-bar-input").val();
console.log(submittedZip);
$.ajax({
url: MyAjax.ajaxurl,
type: "POST",
dataType: "json",
data: {
action: 'zip_search',
submittedZip: submittedZip,
},
success: function (response) {
console.log("this is the response: " + response);
alert("working");
},
})
})
})
To find out what is going wrong, check the error.log of your php server..?

How can I get my Wordpress plugin to receive data and relay it in an ajax/php request to a remote server that requires authentication?

I have written a Wordpress plugin which places several buttons inside a metabox on the post-edit page. I'd go to example.com/wp-admin/post.php?post=number1&action=edit. I want my Wordpress hook to receive an AJAX call, and in turn makes a request to a remote server (one which requires authentication that the WP user shouldn't have to enter), then returns the result to the Wordpress user.
My code for the form with the data I want to send is two custom HTML elements' entered data. They are:
class MyFormData extends HTMLElement{
constructor() {
super();
}
connectedCallback(){
const li = document.createElement('li');
const newDat = document.createElement('input');
newDat.setAttribute('type','text');
newDat.setAttribute('name',`title box`);
newDat.setAttribute('placeholder',`Test Data`);
const deleteButton = document.createElement('button');
deleteButton.setAttribute('type','button');
deleteButton.innerHTML = "-";
deleteButton.addEventListener("click",function(){
li.parentNode.remove();
});
li.appendChild(newDat);
li.appendChild(deleteButton);
this.appendChild(li);
}
}
customElements.define('form-data',MyFormData);
and
class DurationMenu extends HTMLElement{
constructor(){
super();
}
connectedCallback(){
const amount = document.createElement('input');
amount.setAttribute('id','selectedTime');
amount.setAttribute('type','number');
amount.setAttribute('step',5)
amount.setAttribute('name','duration');
amount.setAttribute('min',5);
amount.setAttribute('max',60);
amount.setAttribute('value',15);
this.appendChild(amount)
}
}
customElements.define('duration-choice', DurationMenu);
Both of these custom elements show up in the metabox. I have a custom element for the submit button:
import ModelObject from './model/modelobject.js'
var theJson;
var data;
import {CO} from './Controller/controllerobject.js';
export var c = new ModelObject();
import {grabDataForSending} from './Controller/wordpressrelay.js';
export class SubmitAndCreate extends HTMLElement{
constructor(){
super();
}
connectedCallback(){
var data;
const submitbutton = document.createElement('button');
submitbutton.setAttribute('type','submit');
submitbutton.setAttribute('id','submitButton');
submitbutton.innerHTML = "Begin ";
submitbutton.addEventListener('click',this.myFunc.bind(this));
submitbutton.addEventListener('click',()=>{
document.getElementById('selectedTime').value = 15;
var dataset = document.getElementById("dataset").children;
for(var i = 0; i < dataset.length; i++){
document.getElementById("dataset").children[i].children[0].childNodes[0].value = '';
}
});
submitbutton.addEventListener('click',(event)=>{
CO.updateModelData();
event.preventDefault();
})
submitbutton.addEventListener('click',(event)=>{
grabExperimentForSending();
})
this.appendChild(submitbutton);
}
gatherData(){
//var enteredURL = document.getElementsByName('URL box')[0].value;
var dataAmount = document.getElementById('dataset').children.length;
var experTime = document.getElementById('selectedTime').value;
var dataObject = {
experimentDuration : experTime,
myData: {}
}
var individualDatum = [];
for (var i = 0; i < dataAmount; i++){
individualDatum[i] = {
dataset: document.getElementById("dataset").children[i].children[0].childNodes[0].value
}
}
dataObject.myData = individualDatum;
var dataObjectJSON = JSON.stringify(dataObject,null,2);
theJson = dataObjectJSON;
return theJson;
}
}
export {theJson, CO};
customElements.define('submit-button', SubmitAndCreate)
I want to grab the data one enters in both, and submit it to an external site that normally requires a password and username to login to from outside Wordpress. I want to submit it as JSon. How can I do this with Ajax and php?
My php so far is:
//for admin-ajax
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) {
return;
}
wp_enqueue_script( 'ajax-script', plugins_url( '/wp-content/plugins/my-plugin/js/Controller/ajaxdata.js', __FILE__ ), array('jquery') );
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'c' => c ) ); //c has the data that I need to send to the remote site's server
}
//relevant to admin-ajax
add_action( 'wp_ajax_CBAjax', 'CBAjax' );
//relevant to admin-ajax
function CBAjax() {
error_log(print_r($_REQUEST));
if ( isset($_REQUEST) ) {
$exper = $_REQUEST['experdata'];
error_log(print_r($exper,true));
echo "The exper is " . $exper;
}
$body = array(
'dur' => $exper['experimentDuration'],
'buckets'=> $experdata['myData']
);
$response = wp_remote_post( $url = "https://subdomain.example.com:8080/api/v1/data", array(
'body' => $body,
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( "login#example.com" . ':' . "password!" ),
),
) );
if($response){
error_log(print_r($response,true));
error_log("PING");
}
$respcode = wp_remote_retrieve_response_code($response);
error_log(print_r($respcode,true));
$ajax['remote_code'] = $response['response']['code'];
echo json_encode( $ajax );
error_log(print_r($ajax,true));
wp_die();
}
in the creation of the metabox, I have:
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
add_action( 'wp_ajax_CBAjax', 'CBAjax' );
This is how I proxy the data from the button to the admin-ajax.php page:
import {c} from '../submitbutton.js';
function grabExperimentForSending(){
$.ajax({
url: "admin-ajax.php",
type: "POST",
data: c ,
success: function (response, statusCode) {
console.log(c.exps[0]);
console.log(`statusCode is ${statusCode}`);
console.log(`data is ${data}`);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(`jqXHR is ${jqXHR}, textStatus is ${textStatus}, errorThrown is ${errorThrown}`);
console.log(c.exps[0]);
}
});
}
and from there, it goes to ajaxdata.js
import {c} from './wordpressrelay.js';
function my_action_javascript(){
$('#submitButton').click( function(){
var data = { //model
'action': 'CBAjax',
'experdata': ajax_object.c
}
jQuery.post(ajax_object.ajax_url, data, function(response) {
console.log('Got this from the server: ' + response);
console.log(data.experdata);
console.log(`data[experdata] is ${data['experdata']}`);
});
});
}
export {my_action_javascript,c};
export {grabExperimentForSending,c};
I want to send that data, exp (a Json) to the remote site.
You will need to trigger an ajax request, for example when button click, to your ajax handler.
$('#my-submit-button').click(function(){
var data = {
'action': 'cbAjax',
'experdata': c.exps[0]
};
// from php generate your ajaxurl from admin_url( 'admin-ajax.php' );
jQuery.post(ajaxurl, data, function(response) {
// ajax response if any
});
});
Simply log something in your ajax handler to see if a request is sent after click the button. This is to verify your ajax handler is reachable.

POST admin-ajax throwing error 400 - not finding custom functions

I am adding a function that should be called when a button is clicked, i have a js file with the following jquery code and the ajax call :
jQuery(document).ready( function() {
function getUrlParameter(sParam){
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
jQuery('#upload_btn').click( function(e) {
e.preventDefault();
var flag = true;
var postId = getUrlParameter('preview_id');
var files = jQuery('#file_tool').prop('files');
console.log(files);
var dataS = {
'action': 'upload_button',
'preview_id': postId,
'files': files,
'set': flag
}
jQuery.ajax({
type : 'post',
url : diario.upload,
processData: false,
contentType: false,
data : dataS,
success: function(response) {
if(response.type == "success") {
console.log('jquery works');
} else console.log(response);
}
});
});
});
When i click the button the console.log shows the files obj so at least the onClick works, but just after that it shows up jquery.js:4 POST custom/wp-admin/admin-ajax.php 400. This is how my functions.php looks like :
add_action( 'wp_enqueue_scripts', 'enqueue_onClick_upload' );
//custom_js_enqueuer
function enqueue_onClick_upload() {
wp_register_script( 'onClick_upload', WP_CONTENT_URL.'/themes/microjobengine/onClick_upload.js', array('jquery') );
wp_localize_script( 'onClick_upload', 'diario', array( 'upload' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'onClick_upload' );
}
add_action('wp_ajax_upload_button', 'upload_button');
add_action('wp_ajax_nopriv_upload_button', 'upload_button');
// upload button function
function upload_button() {
$postID = $_POST['preview_id'];
if ($_POST['set']) {
if($_POST['files']['size'] === 0 )
echo "<script>console.log('There's no images.');</script>";
}
$result['type'] = 'success';
echo json_encode($result);
wp_die();
}
I have no idea why it doesn't find the action, it's all done as wp says it should, I hope somone could give a hand, thanks.
--EDIT--
Okay so now i tried to only pass 'action': 'upload_button', the error does not appear but the response doesn't get success, I did this with all the code inside my function commented and just leaving the las 3 lines, in order to return the success, but it doesn't, so it might find the function but for some reason it doesn't get performed, and of course that means something wrong happens when i pass the extra data, any thoughts about why this happens?
Sorry i wasn't getting the right thing to get feedback from the functions, i just had to delete all echos and save everything i needed into an array and returne it json encoded.

Ajax call in wordpress not working for subscriber user in front site

i have simple wordpress form to add data in custom table in wordpress using Ajax
my jquery code(Ajax code )
jQuery.ajax(ajax_object.ajax_url, {
type: "POST",
data: data,
cache: false,
success: function (response) {
alert(response);
},
error: function (error) {
if (typeof console === "object") {
console.log(error);
}
},
complete: function () {
}
});
my php code to save data
if(!class_exists('bookly_appo_Ajax'))
{
class bookly_appo_Ajax
{
public function __construct()
{
add_action('init', array(&$this, 'init'));
}
public function init()
{
add_action( 'wp_enqueue_scripts', 'enqueue_ajax_booklyapp' );
function enqueue_ajax_booklyapp($hook) {
wp_enqueue_script('ajax-script-booklyapp', plugins_url( '/ajax.js?v='.rand(), __FILE__ ), array('jquery'));
wp_localize_script('ajax-script-booklyapp', 'ajax_object',
array(
'ajax_url' => admin_url('admin-ajax.php')
)
);
}
add_action('wp_ajax_add_category_bookly', 'add_category_bookly_callback');
add_action('wp_ajax_nopriv_add_category_bookly', 'add_category_bookly_callback');
function add_category_bookly_callback() {
$storeid=$_REQUEST['storeid'];
$rows = $wpdb->insert(
$table_category, array(
'store_id' => $storeid,
)
);
$lastid = $wpdb->insert_id;
}
}
}
}
my question is
when login with admin user my ajax work fine but when login with other
user(subscriber user) of my site it's give error "Opps!You do not
have sufficient perissions to access this page"
which type of
accessibility provide to subscriber to used admin-ajax.php file
My guess would be you're not defining the action for privileged and non-priviliged users. Do you have both
add_action( 'wp_ajax_ACTION', 'bookly_appo_Ajax' );
add_action( 'wp_ajax_nopriv_ACTION', 'bookly_appo_Ajax' );
In your php? wp_ajax_nopriv_ACTION is probably what you're missing.

Categories