I am getting an erro while using a chosen jquery function - javascript

I have used used the chosen function in my file but it is given an error when i tried to access this function as follows:
TypeError: $(...).ajaxChosen is not a function
here is the code that i am using :
$.post( woocommerce_admin_meta_boxes_variations.ajax_url, data, function ( response ) {
$( '#bto_config_group_inner .bto_groups' ).append( response );
$( "#bto_ids_" + bto_groups_metabox_count ).chosen();
$( "#bto_ids_" + bto_groups_metabox_count ).ajaxChosen( {
method: 'GET',
url: woocommerce_admin_meta_boxes.ajax_url,
dataType: 'json',
afterTypeDelay: 100,
data: {
action: 'woocommerce_json_search_products',
security: woocommerce_admin_meta_boxes.search_products_nonce
}
}, function (data) {
var terms = {};
$.each( data, function (i, val) {
terms[i] = val;
} );
return terms;
} );
$( 'input#_per_product_pricing_bto' ).change();
$( '#bto_product_data' ).unblock();
$( '#bto_product_data' ).trigger( 'woocommerce_bto_component_added' );
} );
return false;
} );

Have you included https://github.com/meltingice/ajax-chosen in your project? Looks like it is not visible in your code.

You will need to download the file - https://github.com/meltingice/ajax-chosen/blob/master/lib/ajax-chosen.min.js
Place it in your project so that it can be referenced with your other assets and include it using the
<script type="text/javascript" src="path/to/ajax-chosen.min.js"></script>
Ideally you would use NPM to bring down the asset, but just simply copying the file locally will suffice to get you up and running
I was unable to find a CDN link for this file, so its going to have to be done manually.

Related

WordPress: ReferenceError jQuery on YITH POS page

I'm trying to add jQuery to the javascript.js file for a child of woodmart theme, but I keep getting "javascript.js:131 Uncaught ReferenceError: jQuery is not defined".
javascript.js
(function($){
jQuery(document).ready(function($) {
//cart_actions parent container
//for POST requests when user saves a cart
clickparent = document.querySelector(".cart-actions");
clickparent.addEventListener("click", function(e) { // e = event object
let carts = JSON.parse(window.localStorage.getItem('yithPOS_carts'));
if (e.target && (e.target.className == "cart-action cart-action--suspend-and-save-cart cart-action--with-icon") || e.target.className == "cart-action__icon yith-pos-icon-saved-cart") {
// Use ajax to do something...
var postData = {
action: 'wpa_49691',
my_var: 'carts',
}
$.ajax({
type: "POST",
data: postData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
console.log("Cart saved to database.");
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
}
});
//pos_current_Cart_buttons parent container
//for GET requests when user views saved carts
viewcartparent = document.querySelector(".yith-pos-cart__buttons");
viewcartparent.addEventListener("click", function(e) { // e = event object
if (e.target && (e.target.className == "yith-pos-cart__buttons-saved-carts")) {
// Use ajax to do something...
var getData = {
action: 'wpa_49692',
my_var: 'my_data',
}
$.ajax({
type: "GET",
data: getData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
let total;
for(item in response){
total += item[lineTotal];
}
$(".yith-pos-cart__savedcarts").append('</div><i class="yith-pos-cart__savedcart"></i><div class="cart-saved__name"><div class="cart-saved__name__id">' + response['id'] + '</div><div class="cart-saved__name__customer">' + response['cartitems']['names'] + '</div></div><div class="cart-saved__num_of_items">' + response['cartitems'].size + '</div><div class="cart-saved__status">Pending Payment</div><div class="cart-saved__total">'+ total + '</div><button class="btn btn-primary"><i class="yith-pos-icon-refresh"></i> load</button></div>');
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
}
});
// Handler for .ready() called.
});
})(jQuery);
I've also tried enqueuing jquery with wp_enqueue_script and passing jquery in an array to the javascript file, neither changed anything.
functions.php:
wp_enqueue_script('jquery');
//First enqueue your javascript in WordPress
function save_cart_enqueue_scripts(){
//Enqueue your Javascript (this assumes your javascript file is located in your plugin in an "includes/js" directory)
wp_enqueue_script( 'javascript.js', plugins_url('https://cigarchiefstg.wpengine.com/wp-content/themes/woodmart-child/yith-pos-additions/javascript.js', dirname(__FILE__) ), array( 'jQuery' ));
//Here we create a javascript object variable called "youruniquejs_vars". We can access any variable in the array using youruniquejs_vars.name_of_sub_variable
wp_localize_script( 'javascript', 'javascript_vars',
array(
//To use this variable in javascript use "youruniquejs_vars.ajaxurl"
'ajaxurl' => admin_url( 'javascript_vars.ajaxurl' ),
)
);
}
add_action( 'wp_enqueue_scripts', 'save_cart_enqueue_scripts' );
//This is your Ajax callback function
function cart_save_callback_function(){
//Get the post data
$my_var = $_POST["my_var"];
//Do your stuff here - maybe an update_option as you mentioned...
update_option('saved_carts', $my_var);
//Create the array we send back to javascript here
$return_array = array();
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $return_array );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'wpa_49691', 'cart_save_callback_function' );
add_action( 'wp_ajax_nopriv_' . 'wpa_49691', 'cart_save_callback_function' );
function cart_view_callback_function(){
//Get the post data
$my_var = $_POST["my_var"];
//Do your stuff here - maybe an update_option as you mentioned...
//Create the array we send back to javascript here
$carts = get_option('saved_carts');
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $carts );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'wpa_49692', 'cart_view_callback_function' );
add_action( 'wp_ajax_nopriv_' . 'wpa_49692', 'cart_view_callback_function' );
Edit: Issues with POS items:
first check if jquery is correctly loaded on you wp website.
I suggest using this syntax for jQuery:
(function($){
$(document).ready(function(){
//your code
})(jQuery);

Simple Jquery POST call not working

I got a simple POST call to a PHP file on my website. For some reason it's not working though. The console.log shows"undefined"
function check() {
var url = "../API/keychecker.php";
var spullen = $("keyval").val;
$.ajax({
type: "POST",
url: url,
data: {
key: spullen
},
success: function(data) {
console.log(data);
}
})
}
Here is the PHP file:
<?php
echo json_encode($_POST['key']);
?>
Your keyval call doesn't specify the type of element identifier. jQuery won't find the element you're looking for as you currently have it.
You must specify:
For classes:
$( ".keyval" ).val();
For ID
$( "#keyval" ).val();
For input name
$( "input[name=keyval]" ).val();
That should attach the value to the POST request.
var url = "API/keychecker.php";
var spullen = $( "keyval" ).val();

Class Yii is not found when posting a variable with ajax

I want to get a variable from ajax to php. I'm using the Yii framework.
So my problem is, when I want to transfer a variable from ajax to a php script I get this error:
Fatal error: Class 'Yii' not found in
/var/www/vhosts/adappter.de/comamos/protected/views/store/search_area.php
on line 44 store.js:1308:13
This is how my Ajax Call looks like
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "../protected/views/store/search_area.php",
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});
and this is my php script to line 44
<?php
if (!isset($_SESSION)) { session_start(); }
$_SESSION['search_type']='';
if (isset($_GET['s'])){
$_SESSION['kr_search_address']=$_GET['s'];
$_SESSION['search_type']='kr_search_address';
}
unset($_SESSION['kr_item']);
unset($_SESSION['kr_merchant_id']);
$marker=Yii::app()->functions->getOptionAdmin('map_marker');
if (!empty($marker)){
echo CHtml::hiddenField('map_marker',$marker);
}
?>
The jQuery call is only when I click on a checkbox. So the value of the selected box gets pushed in an array. I want to return the array to the php script.
When I'm loading the site, I don't get such an error. So I don't know why this error occurs.
You need to use controller with action. Not only view file. You try to call view file from web. But it is wrong, because all code in protected directory. All requests must processing from index file. In index file connected framework. Here a small example. Controller:
class SiteController extends Controller
public function actionTest()
{
//... example
echo CHtml::button('test');
}
js:
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "/site/test", // url for your action
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});

$.ajax() .then() isn't being executed

I'm trying to execute the remote code completion example in Jquery Mobile using the following url: http://demos.jquerymobile.com/1.4.0/listview-autocomplete-remote/
I use latest PhoneGap with jquery mobile version 1.4.3
the auto complete javascript code:
$(function() {
$( "#drink_brand_autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://myalcoholist.com/drink-management/drink/drink-brand-autocomplete",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then( function ( response ) {
console.log("response");
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
console.log(html);
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
in chrome developer console i can see that the ajax call is being executed fine and the server returns a json array.
the .then() is not being executed, no ideas why.
i tried .done() instead but i got the same results.
i don't get any javascript errors.
any ideas?

AJAX: Can't pass javascript variable to SQL query in PHP script

I have a PHP page with 2 sections side by side. The left pane has a MySQL query that runs and produces a list of categories as links. The right pane should have subcategories that appear when links in the left pane are clicked.
I have some AJAX in an attached JS file that should pass the ID in the links from the left pane, into a query in the right pane. The query should run. It runs if I take out a variable.
The PHP/SQL Queries work fine. JS does not.
I think this is the appropriate way of doing this.
ajax.js
$( document ).ready(function() {
$( 'a' ).on( 'click', function() {
var a = $( this ).attr( 'id' );
$.ajax({
type: "POST",
url: "categories.php",
data: "ajax="+a,
success: function(response){
alert( a );
},
error: function() {
alert('Error');
}
})
});
});
I am being told everything works, but I cannot call $_POST['ajax'] in PHP. Perhaps my page is not being refreshed. There is no form on the page.
Lastly, my file hierarchy has categories.php comprised of a list of includes, which are in a folder that is not public.
I think your ajax syntax is wrong. Try this if your argument is a and your post identifier is ajax:
$( document ).ready(function() {
$( 'a' ).on( 'click', function() {
var a = $( this ).attr( 'id' );
$.ajax({
type: "POST",
url: "categories.php",
data: {ajax : a},
success: function(response){
alert( a );
},
error: function() {
alert('Error');
}
});
});
});
Try setting async: false on your $.ajax call. Also, how is the data being return from php? Are you using JSON_ENCODE for the data?

Categories