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..?
Related
I'm building my first wordpress plugin and I'm having trouble converting a Javascript array of objects into PHP so I can use the data to create individual tables in the wp-admin user area.
Before i actually include the object, i thought i'd try with just a single variable.
Firstly, i included the wp-admin/admin-ajax.php url in wp_localize_script to use in my Javascript file.
function addition_js_script() {
wp_enqueue_script(
'dynamic-maths-addition-js',
DYNAMIC_MATHS_URL . 'includes/shortcodes/addition/addition.js',
['jquery'],
time(),
true
);
wp_localize_script( 'dynamic-maths-addition-js', 'php_data', array(
'user_addition_skill' => get_user_meta( wp_get_current_user()->ID, 'addition-skill-level', true ),
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
}
if (shortcode_exists( 'addition_quiz' ) ){
add_action( 'wp_enqueue_scripts', 'addition_js_script', 100 );
add_action( 'wp_enqueue_scripts', 'addition_css_script', 100 );
}
Then, in addition.js:
jQuery(document).ready(function($){
let numTest = '75';
jQuery.ajax({
url: php_data.ajaxurl,
data: {
'action': 'php_test',
'php_test': numTest
},
success: function(data){
console.log('happy');
}
});
});
Then in my backend menu.php file:
function retrieve_test_number(){
if (isset($_REQUEST)){
$num = $_REQUEST['php_test'];
echo 'This is our JS variable: ' . $num;
}
die();
}
add_action('wp_ajax_php_test_num', 'retrieve_test_number');
Like this, it displays "This is our JS variable: " but no number displays.
And even when I try return this function with the variable $num, and i try echo it out in a tag further down the page, i can't get the variable to display. Forgive me for any ignorance, my php skills are terrible.
Change add_action('wp_ajax_php_test_num', 'retrieve_test_number'); to add_action('wp_ajax_php_test', 'retrieve_test_number');. check below code.
HTML
<p id="num"></p>
Javascript
jQuery(document).ready(function($){
let numTest = '75';
jQuery.ajax({
url: php_data.ajaxurl,
data: {
'action': 'php_test',
'php_test': numTest
},
success: function(data){
console.log('happy');
$('#num').html(data);
}
});
});
PHP
function retrieve_test_number(){
if (isset($_REQUEST)){
$num = $_REQUEST['php_test'];
echo 'This is our JS variable: ' . $num;
}
die();
}
add_action('wp_ajax_php_test', 'retrieve_test_number');
add_action( 'wp_ajax_nopriv_php_test', 'retrieve_test_number' );
Tested and works.
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
I have used Wordpress Admin Ajax and the console shows that 400 (Bad Request)
jQuery('#submitid').click(function(e){
e.preventDefault();
//var newCustomerForm = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
data: {status: 'status', name: 'name'},
success:function(data){
jQuery("#result").html(data);
}
});
});
The Wordpress AJAX process has some basic points that should be followed if you want it to work correctly:
1.In functions.php add the action you'd like to call from the frontend:
function logged_in_action_name() {
// your action if user is logged in
}
function not_logged_in_action_name() {
// your action if user is NOT logged in
}
add_action( 'wp_ajax_logged_in_action_name', 'logged_in_action_name' );
add_action( 'wp_ajax_nopriv_not_logged_in_action_name', 'not_logged_in_action_name' );
2.Register the localization object in functions.php
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$some_object = array(
'ajax_url' => admin_url( 'admin-ajax.php' )
);
wp_localize_script( 'some_handle', 'ajax_object', $some_object );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
3.Create the AJAX request on the frontend
// source: https://codex.wordpress.org/AJAX_in_Plugins
var data = {
'action': 'not_logged_in_action_name',
'whatever': 1234
};
jQuery.post( ajax_object.ajax_url, data, function( response ) {
console.log( response );
}
All Wordpress Ajax call must have action param which points to hook wp_ajax_{action_param} or wp_ajax_nopriv_{action_param} and from there you jump to function from that hooks.
From Codex:
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action() {
$status = $_POST['status'];
}
first you shouldn't write the url by yourself. You could use the localize function to add the url to your javascript file:
wp_enqueue_script('myHandle','pathToJS');
wp_localize_script(
'myHandle',
'ajax_obj',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
After this you can use ajax_obj.ajax_url within your script to receive the url.
Second, did you implement the correct hook?
// Only accessible by logged in users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// Accessible by all visitors
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
Best Regards
I try to use woocommerce Ajax, I find a lot example online, none of them works.
could someone take a look on my code, where's the problem.
add_action( 'wp_ajax_my_action', 'mmy_real' );
add_action( 'wp_ajax_nopriv_my_action', 'mmy_real' );
function mmy_real(){
check_ajax_referer( 'my-special-string', 'security' );
$make = $_SESSION['vpf']['search']['make'];
$model = $_SESSION['vpf']['search']['model'];
$year = $_SESSION['vpf']['search']['year_id'];
die();
}
function mmy_script(){
wp_register_script( "hover_script", get_template_directory_uri() . '/js/mmy.js', array('jquery'), '1.0.0', true );
wp_localize_script( 'hover_script', 'mmy', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),'security' => wp_create_nonce( 'my-special-string' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'hover_script' );
}
add_action('init', 'mmy_script');
jQuery(document).ready(function() {
jQuery.ajax({
type: "post",
url : mmy.ajaxurl,
data:{
action:"mmy_real",
make: "make",
model: "model",
year: "year"
},
success: function( response ) {
alert("success");
}
});
});
I test in localhost. It won't alert success messagebox, if I change url to localhost/fhgroupauto/test.php . it will alert success .
I don't know what do i miss for this .
Thanks
The value of "action" is wrong.
You add the hook "wp_ajax_my_action" and "wp_ajax_nopriv_my_action", so the string after "wp_ajax_" and "wp_ajax_nopriv_" is the parameter for the "action" key.
Which means your data array for the ajax call should look like this:
data:{
action: "my_action",
make: "make",
model: "model",
year: "year"
},
For more information see the Wordpress documentation - AJAX in Plugins
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.