woocommerce ajax in the front-end not working - php

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

Related

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..?

My function containing a mysql query launched by ajax is not working in wordpress. What am I missing?

I am trying to insert rows into a table I've set up based on user's answers. I have made a child theme and a custom template for the page with the form. My issue is that I have no way of knowing what's going wrong where and why the data isn't being inserted. my js onclick function is as follows, and this file is called question_submit.js:
jQuery(document).ready(function(){
jQuery("#questionSubmit").click(function(){
alert("clicked");
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: my_ajax_object.ajax_url,
data: {
'action' : 'dbtest',
'option': 1,
},
success: function(data){
alert(data);
}
});
})
});
Here is where I enqueue the script:
function my_enqueue() {
wp_enqueue_script( 'question_submit', get_stylesheet_directory_uri() . '/assets/js/question_submit.js', array('jquery') );
wp_localize_script( 'question_submit', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
And finally here is the function that's binded to the action:
function dbtesting(){
global $wpdb;
$data = $_POST['data'];
//$option = sanitize_text_field($_POST["option"]);
$tableName = 'user_answers';
$insert_row = $wpdb->insert(
$tableName,
array(
'user_id' => 2,
'module_id' => 3,
'section_id' => 1,
'question_id' => 2,
'option_no' => 1,
)
);
// if row inserted in table
if($insert_row){
echo json_encode(array('res'=>true, 'message'=>__('New row has been inserted.')));
}else{
echo json_encode(array('res'=>false, 'message'=>__('Something went wrong. Please try again later.')));
}
wp_die();
}
add_action( 'wp_ajax_dbtest', 'dbtesting' );
add_action( 'wp_ajax_nopriv_dbtest', 'dbtesting' );
Both of these functions are in my child theme's functions.php file. Right now I am using hard-coded values jsut to test the functionality, later these values will be dependent on the form answers.
When I click the submit button, there is no change in my table but also no php errors.

Wordpress Admin Ajax 400 (Bad Request)

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

Cannot Get AJAX To Load

Here is HTML Nav:
<ul class="sub-menu side-nav page-sidebar child-pages">
<li class="menu-item menu-item-type-post_type menu-item-object-post menu-item-9045" data-id="105"><span class="menu-image-title">History</span></li>
<li class="menu-item menu-item-type-post_type menu-item-object-post menu-item-9046" data-id="185"><span class="menu-image-title">Strategic Plan</span></li>
<li class="menu-item menu-item-type-post_type menu-item-object-post menu-item-9047" data-id="183"><span class="menu-image-title">Financial Statements</span></li>
</ul>
Here is my PHP function:
add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' );
function my_load_ajax_content(){
$post_id = $_POST[ 'post_id' ];
$post = get_post( $post_id, OBJECT);
$response = array( apply_filters( 'the_content', $post->post_title ), apply_filters( 'the_content', $post->post_content ) );
echo '<div class="entry-header"><h1 class="entry-title">'.$response[0].'</h1></div><div class="entry-content">'.$response[1].'</div>';
die(1);
}
wp_enqueue_script( 'my-ajax-request', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
Here's what's in ajax.js:
jQuery(document).ready(function($) {
$(window).on('load',Foundation.utils.throttle(function(e){
if($('.current-menu-item > .sub-menu')){
$('#sidebar-b').append($('.current-menu-item > .sub-menu').addClass('side-nav page-sidebar child-pages'));
$("#sidebar-b .menu-item a:not(.pdf)").each(function(){
var link_text = $(this).children('.menu-image-title').html();
$(this).attr('href','#'+link_text);
});
}
},300));
$("#sidebar-b .menu-item .menu-image-title-after").click(function(e) {
$("#loading-animation").show();
var post_id = $(this).parent("li").attr("data-id");
var ajaxURL = MyAjax.ajaxurl;
$.ajax({
type: 'POST',
url: ajaxURL,
data: {"action":"load-content",post_id:post_id},
success: function(response){
$("#content > article").html(response);
$("#loading-animation").hide();
return false;
}
});
});
});
Additionally, when checking the <head> I noticed that my ajax.js script is not even loading even though it's being enqueued in my PHP function. Any ideas on what I'm doing wrong? I've scoured Google for the last 3 hours and haven't found an exact answer.
1, you have to make sure that your script is triggered at the right element
2, you should change : "action":"load-content" to action: 'load-content' ( remove the double quote at action )
You need to enqueue the scripts by using below mentioned way, then it will be hooked with wp_enqueue_scripts hook and load properly :
function load_scripts() {
wp_enqueue_script( 'my-ajax-request', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'load_scripts' );
Hope it helps you.
Ultimately, after days and days of trial and error, I FINALLY got AJAX working! The secret was making my ajax.js an anonymous function.
(function($){
$(document).on('click','.ajax-click',function(e){
e.preventDefault();
var post_id = $(this).parent().attr('data-id');
var ajaxURL = MyAjax.ajaxurl;
$.ajax({
cache: false,
type: "POST",
url: ajaxURL,
data:{ action: "load_content", post_id: post_id },
beforeSend: function(){
$("#loading-animation").show();
$("#content > article").fadeOut();
},
success: function(response){
$("#content > article").html(response).fadeIn();
$("#loading-animation").hide();
return false;
}
});
});
})(jQuery);
I kept everything in my ajaxify.php file as follows:
add_action ( 'wp_ajax_nopriv_load_content', 'my_ajax_load_content', 99 );
add_action ( 'wp_ajax_load_content', 'my_ajax_load_content', 99 );
function my_ajax_load_content(){
$post_id = $_POST[ 'post_id' ];
$post = get_post( $post_id );
$response = array( apply_filters( 'the_content', $post->post_title ), apply_filters( 'the_content', $post->post_content ) );
echo '<div class="entry-header"><h1 class="entry-title">'.$response[0].'</h1></div><div class="entry-content">'.$response[1].'</div>';
die(0);
}
wp_enqueue_script( 'my-ajax-request', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
Quick reminder: Your action in PHP MUST match your action inside you jQuery. In my case it was load_content (e.g. wp_ajax_nopriv_load_content, wp_ajax_load_content, data:{ action: "load_content" }).
Hopefully this helps someone going through a similar issue with WordPress AJAX.

Need help spotting the mistake in either jQuery or php in wordpress

I'm having trouble trying to figure out which part of my code is wrong, taking into account there are several languages involved.
Firstly I enqueue the script that I am going to run and then use wp_localize_script in the plugin main function file as follows:
// All scripts
add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );
function theme_enqueue_scripts() {
// Enqueue and Localize AJAX JavaScript Functions File
wp_enqueue_script( 'ajax-categories-js', plugins_url( 'events-calendar-manager/inc/js/js.js' ), array('jquery'));
wp_localize_script( 'ajax-categoreis-js', 'ajax_object_1', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
}
The jQuery script looks like this:
// JavaScript Document
jQuery(document).ready(function($){
console.log('Started Jquery');
var year='', month='', category='';
$('#next_link').click(function(e){
e.preventDefault();
var $aid =$('#next_link');
year =$aid.data('year');
month =$aid.data('month');
category =$aid.data('category');
console.log('category: ' + category);
});
$('#previous_link').click(function(e){
e.preventDefault();
var $dai =$('#previous_link');
year =$dai.data('year');
month =$dai.data('month');
category =$dai.data('category');
console.log('category: ' + category);
});
console.log('category: ' + category);
$.ajax({
cache: false,
timeout: 8000,
type: 'POST',
data: {action: 'get_post_filter_by_date_and_category', year : year, month: month, category: category},
url: ajax_object_1.ajaxurl,
success: function(data) {},
error: function() {}
});
});
However when I run it I get a mistake in the console saying : Uncaught ReferenceError: ajax_object_1 is not defined . This is weird as the object should be passed on using the wp_localize_script function.
What creates this problem?
You have a typo here
wp_enqueue_script( 'ajax-categories-js' ...
wp_localize_script( 'ajax-categoreis-js', ...
See ajax-categories-js !== ajax-categoreis-js
wp_localize_script( 'ajax-categories-js', 'ajax_object_1', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
Don't know nada about WP, but it looks like you have a typo here:
wp_localize_script( 'ajax-categoreis-js', 'ajax_object_1', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
You probably didn't mean to write ...'ajax-categoreis-js'... but ...'ajax-categories-js'...

Categories