I uploaded the dropdown to my web site, somehow it looks double:)
Like this:
But, that's not the only problem,
Another problem is that Elements do not appear in the <select> list, but when I add some sample <option>Sample</option> all elements appear.
My Select Codes:
<select class="selectpicker" id="List" multiple data-live-search="true" data-actions-box="true" data-selected-text-format="count>1">
<option>asdd</option>
<option>3</option>
<option>ssasd</option>
<option>adsd</option>
<option>a</option>
<option>sasd</option>
<option>adsd</option>
</select>
My JavaScript code:
$.ajax({
type : "POST",
url : "db/../..",
dataType : "json"
})
.done(function( result ) {
if ( typeof result.error !== "undefined" ) {
// Error
dialog.close();
alertDialog( "Hata", result.error, BootstrapDialog.TYPE_DANGER );
} else if ( typeof result.List !== "undefined" && $.isArray( result.List ) ) {
// A proper result
if ( result.FirmList.length < 1 ) {
// No records found
dialog.close();
alertDialog( "Error", "Nothing Found!", BootstrapDialog.TYPE_WARNING );
} else {
// Parse details
var f = result.List;
for ( var i = 0; i < f.length; i++ ) {
var op = document.createElement( "option" );
op.value = f[ i ].Id;
op.textContent = f[ i ].Name;
document.getElementById( "List" ).appendChild( op );
}
$( "#select" ).chosen();
}
} else {
dialog.close();
alertDialog( "Error", "No Idea!", BootstrapDialog.TYPE_DANGER );
}
})
.fail(function(a, b, c) {
dialog.close();
alertDialog( "Error",
"Error",
BootstrapDialog.TYPE_DANGER );
});
Related
NOTE:: I have replaced some code with comments to make it much shorter and more readable
I am working with Javascript (Ajax) and PHP (Laravel). I have run into a predicament! When calling an ajax function I have two listener to show a loading symbol while the ajax is processing, and then hide it again once it's done.
$( document ).ajaxStart( function() {
$( '#loading' ).css( 'display', 'block' );
} );
$( document ).ajaxStop( function() {
$( '#loading' ).css( 'display', '' );
} );
When you click on the submit button, the HTML onclick says to go to this function which is working just fine:
function submit( button ) {
var table = $( button ).closest( '.popup' ).find( 'table:first' );
var verified = verifyTable( table );
if ( verified == -1 ) {
return -1;
}
if ( table.hasClass( 'campaigns' ) ) {
campaign = table.find( '.campaign:first' );
submitNewCampaign( campaign );
} else if ( table.hasClass( 'groups' ) ) {
groups = table.find( 'tr.group' );
for ( var i = 0; i < groups.length; ++i ) {
submitNewGroup( groups.eq( i ) );
}
} else if ( table.hasClass( 'keywords' ) ) {
keywords = table.find( 'tr.keyword' );
for ( var i = 0; i < keywords.length; ++i ) {
submitNewKeyword( keywords.eq( i ) );
}
}
closePopup();
}
If from there you are sent to submitNewCampaign(), everything works just fine.
function submitNewCampaign( campaign ) {
// Set campaign variables
$.ajax({
url : '/ajax/addCampaign',
type : 'POST',
data : { // set campaign data },
success : function( result ) {
// get all groups in campaigns and loop through
for ( var i = 0; i < groups.length; ++i ) {
// set group variables
$.ajax({
url : '/ajax/addGroup',
type : 'POST',
async : false,
data : { // set group data },
success : function( result ) {
// get all keywords in group and loop
for ( var i = 0; i < keywords.length; i++ ) {
// set keyword variables
$.ajax({
url : '/ajax/addKeyword',
type : 'POST',
async : false,
data : { // set keyword data },
success : function( result ) { // done },
error : function( result ) {
alert( "error adding new keyword (name - " + keyword_name + ")");
console.log( result );
}
);
}
},
error : function( result ) {
alert( "error adding new group (name - " + group_name + ")" );
console.log( result );
}
});
}
},
error : function( result ) {
alert( "error adding new campaign (name - " + campaign_name + "): " + JSON.parse( xhr.responseText ) );
}
});
}
However if you are send to either submitNewGroup() or submitNewKeyword(), the loading image does not appear.
function submitNewGroup ( group ) {
// set group variables
$.ajax({
url : '/ajax/addGroup',
type : 'POST',
async : false,
data : { // set group data },
success : function( result ) {
// get all keywords in group and loop
for ( var i = 0; i < keywords.length; ++i ) {
// set all keyword variables
$.ajax({
url : '/ajax/addKeyword',
type : 'POST',
async : false,
data : { // set all keyword data },
success : function( result ) { // done },
error : function( result ) {
console.log( result );
}
});
}
},
error : function( result ) {
console.log( result );
}
});
}
function submitNewKeyword( keyword ) {
// set keyword variables
$.ajax({
url : '/ajax/addKeyword',
type : 'POST',
async : false,
data : { // set keyword data },
success : function( result ) { //done },
error : function( result ) {
console.log( result );
}
});
}
IMPORTANT: No errors appear in the log when any of the three functions are called. All three complete their assigned tasks with no issues.
I tried a few things and the one that made it work was: I removed async from the outer most ajax call for both group and keyword
I installed an plugin on my current clean wordpress installation. However I always get the following error as soon as the widget for the plugin gets laoded
TypeError: $ is not a function
I checked the js files for the addon and they all seem to make proper use of jQuery instead of $ also the register_script function requires jquery as dependency
Below you can see the add_action function
if (!is_admin()) {
function woocommerce_ogonecw_add_frontend_css() {
wp_register_style('woocommerce_ogonecw_frontend_styles', plugins_url('resources/css/frontend.css', __FILE__));
wp_enqueue_style('woocommerce_ogonecw_frontend_styles');
true);
wp_register_script('ogonecw_frontend_script', plugins_url('resources/js/frontend.js', __FILE__), array(
'jquery'
));
wp_enqueue_script('ogonecw_frontend_script');
wp_localize_script('ogonecw_frontend_script', 'woocommerce_ogonecw_ajax',
array(
'ajax_url' => admin_url('admin-ajax.php')
));
}
add_action('wp_enqueue_scripts', 'woocommerce_ogonecw_add_frontend_css');
frontend.js looks like this
jQuery(function (jQuery) {
var isSubmitted = false;
var CheckoutObject = {
cssClass: '',
successCallback: '',
placeOrder: function() {
var form = jQuery('form.checkout');
var form_data = form.data();
// WGM: Back Button
if(jQuery("input[name=cw-wgm-button-back]").length > 0) {
return true;
}
//WGM: MultiStep
if(jQuery("input[name=wc_gzdp_step_submit]").length > 0) {
if(jQuery("input[name=wc_gzdp_step_submit]").val() == "address"){
return true;
}
}
var selectedPaymentMethodElement = jQuery('input:radio[name=payment_method]:checked');
var selectedPaymentMethod = selectedPaymentMethodElement.val();
var secondRun = false;
if(jQuery("input[name=ogonecw_payment_method_choice]").length > 0) {
secondRun = true;
selectedPaymentMethodElement = jQuery("input[name=ogonecw_payment_method_choice]");
selectedPaymentMethod = selectedPaymentMethodElement.val();
}
var moduleName = 'ogonecw';
var selectedModuleName = (selectedPaymentMethod != undefined) ?
selectedPaymentMethod.toLowerCase().substring(0, moduleName.length) : '';
onOgoneCwCheckoutPlaceObject = this;
if (moduleName == selectedModuleName) {
form.addClass('processing');
if ( form_data["blockUI.isBlocked"] != 1 ) {
form.block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
}
this.successCallback = previewAuthorization;
this.cssClass = 'ogonecw-preview-fields';
onOgoneCwCheckoutPlaceObject = this;
if(secondRun) {
this.generateOrder(form, selectedPaymentMethod);
return false;
}
var validateFunctionName = 'cwValidateFields'+selectedPaymentMethod.toLowerCase();
var validateFunction = window[validateFunctionName];
if (typeof validateFunction != 'undefined') {
validateFunction(function(valid){onOgoneCwCheckoutPlaceObject.successCall();}, function(errors, valid){onOgoneCwCheckoutPlaceObject.failureCall(errors, valid);});
return false;
}
onOgoneCwCheckoutPlaceObject.successCall();
return false;
}
},
failureCall: function(errors, valid){
alert(errors[Object.keys(errors)[0]]);
var form = jQuery('form.checkout');
form.removeClass('processing').unblock();
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
},
successCall : function(){
var form = jQuery('form.checkout');
var selectedPaymentMethodElement = jQuery('input:radio[name=payment_method]:checked');
var selectedPaymentMethod = selectedPaymentMethodElement.val();
onOgoneCwCheckoutPlaceObject = this;
if(selectedPaymentMethodElement.parents('li').find('.ogonecw-validate').length > 0){
var ajaxUrl;
if(typeof wc_checkout_params != 'undefined') {
ajaxUrl = wc_checkout_params.ajax_url;
}
if(typeof checkoutUrl == 'undefined') {
ajaxUrl = woocommerce_params.ajax_url;
}
var separator = ajaxUrl.indexOf('?') !== -1 ? "&" : "?";
ajaxUrl = ajaxUrl+separator+"action=woocommerce_ogonecw_validate_payment_form";
var inputData = getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase());
var postData = "&";
jQuery.each(inputData, function(key, value) {
postData += encodeURIComponent(key)+"="+encodeURIComponent(value)+"&";
});
jQuery.ajax({
type: 'POST',
url: ajaxUrl,
data: form.serialize()+postData+ onOgoneCwCheckoutPlaceObject.cssClass + "=true",
success: function( code ) {
var response = '';
try {
response = jQuery.parseJSON(code);
if ( response.result == 'success' ) {
onOgoneCwCheckoutPlaceObject.generateOrder(form, selectedPaymentMethod);
return false;
}
else if ( response.result == 'failure' ) {
throw 'Result failure';
} else {
throw 'Invalid response';
}
}
catch(err ){
// Remove old errors
jQuery( '.woocommerce-error, .woocommerce-message' ).remove();
// Add new errors
if ( response.message ) {
form.prepend(response.message);
} else {
form.prepend(code);
}
// Cancel processing
form.removeClass( 'processing' ).unblock();
// Lose focus for all fields
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
// Scroll to top
jQuery( 'html, body' ).animate({
scrollTop: ( jQuery( 'form.checkout' ).offset().top - 100 )
}, 1000 );
}
},
dataType: 'html'
});
return false;
}
else {
onOgoneCwCheckoutPlaceObject.generateOrder(form, selectedPaymentMethod);
return false;
}
},
generateOrder: function(form, selectedPaymentMethod) {
onOgoneCwCheckoutPlaceObject = this;
var checkoutUrl;
if(typeof wc_checkout_params != 'undefined') {
checkoutUrl = wc_checkout_params.checkout_url;
}
if(typeof checkoutUrl == 'undefined') {
checkoutUrl = woocommerce_params.checkout_url;
}
jQuery.ajax({
type: 'POST',
url: checkoutUrl,
data: form.serialize() + "&" + onOgoneCwCheckoutPlaceObject.cssClass + "=true",
success: function( code ) {
var response = '';
try {
if (code.indexOf("<!--WC_START-->") >= 0) {
code = code.split("<!--WC_START-->")[1];
}
if (code.indexOf("<!--WC_END-->") >= 0) {
code = code.split("<!--WC_END-->")[0];
}
try {
// Check for valid JSON
response = jQuery.parseJSON( code );
} catch ( e ) {
// Attempt to fix the malformed JSON
var validJson = code.match( /{"result.*"}/ );
if ( null === validJson ) {
throw 'Invalid response';
} else {
response = jQuery.parseJSON(validJson[0]);
}
}
if ( response.result == 'success' ) {
onOgoneCwCheckoutPlaceObject.successCallback(response, selectedPaymentMethod);
}
else if ( response.result == 'failure' ) {
throw 'Result failure';
} else {
throw 'Invalid response';
}
}
catch( err ) {
if ( response.reload === 'true' ) {
window.location.reload();
return;
}
// Remove old errors
jQuery( '.woocommerce-error, .woocommerce-message' ).remove();
// Add new errors
if ( response.messages ) {
form.prepend( response.messages );
} else {
form.prepend( code );
}
// Cancel processing
form.removeClass( 'processing' ).unblock();
// Lose focus for all fields
form.find( '.input-text, select, input:checkbox' ).trigger( 'validate' ).blur();
// Scroll to top
jQuery( 'html, body' ).animate({
scrollTop: ( jQuery( 'form.checkout' ).offset().top - 100 )
}, 1000 );
// Trigger update in case we need a fresh nonce
if ( response.refresh === 'true' ) {
jQuery( 'body' ).trigger( 'update_checkout' );
}
jQuery( 'body' ).trigger( 'checkout_error' );
}
},
dataType: 'html'
});
},
};
var getFormFieldValues = function(parentCssClass, paymentMethodPrefix) {
var output = {};
jQuery('.' + parentCssClass + ' *[data-field-name]').each(function (element) {
var name = jQuery(this).attr('data-field-name');
if(name.lastIndexOf(paymentMethodPrefix, 0) === 0) {
name = name.substring(paymentMethodPrefix.length);
name = name.substring(1, name.length -1 );
if(this.type == "radio") {
if(this.checked) {
output[name] = jQuery(this).val();
}
}
else{
output[name] = jQuery(this).val();
}
}
});
return output;
};
var generateHiddenFields = function(data) {
var output = '';
jQuery.each(data, function(key, value) {
output += '<input type="hidden" name="' + key + '" value="' + value + '" />';
});
return output;
};
var removeNameAttributes= function(cssClass) {
// Remove name attribute to prevent submitting the data
jQuery('.' + cssClass + ' *[name]').each(function (element) {
jQuery(this).attr('data-field-name', jQuery(this).attr('name'));
if(jQuery(this).is(':radio')){
return true;
}
jQuery(this).removeAttr('name');
});
}
var addAlias = function(cssClass){
// Add listener for alias Transaction selector
jQuery('.' + cssClass).parents('li').find('.ogonecw-alias-input-box > select').bind('change', function() {
jQuery('body').trigger('update_checkout');
});
}
var registerCheckoutObject = function(){
bindOrderConfirmEvent(CheckoutObject);
};
var bindOrderConfirmEvent = function (CheckoutObject) {
var form = jQuery('form.checkout');
var attached = form.attr('data-ogonecw-attached');
if (attached != 'true') {
form.attr('data-ogonecw-attached', 'true');
form.bind('checkout_place_order', function() {
return CheckoutObject.placeOrder();
});
return false;
}
};
// We have to make sure that the JS in the response is executed.
jQuery( document ).ready(function() {
if (typeof window['force_js_execution_on_form_update_listener'] === 'undefined') {
window['force_js_execution_on_form_update_listener'] = true;
jQuery('body').bind('updated_checkout', function() {
removeNameAttributes('ogonecw-preview-fields');
addAlias('ogonecw-preview-fields');
if (jQuery('.ogonecw-preview-fields').length > 0) {
registerCheckoutObject();
}
});
}
});
jQuery( document ).ajaxStop(function(event, xhr, settings) {
removeNameAttributes('ogonecw-preview-fields');
addAlias('ogonecw-preview-fields');
if (jQuery('.ogonecw-preview-fields').length > 0) {
registerCheckoutObject();
}
});
var previewAuthorization = function (result, selectedPaymentMethod) {
if(typeof result.redirect !== 'undefined') {
var additionalFields = jQuery('<div class="ogonecw-preview-fields" style="display: none;"></div>');
jQuery('.' + 'ogonecw-preview-fields' + ' *[data-field-name]').each(function (element) {
var name = jQuery(this).attr('data-field-name');
if(name.lastIndexOf(selectedPaymentMethod.toLowerCase(), 0) === 0) {
jQuery(additionalFields).append(jQuery(this));
}
});
var redirectUrl;
if ( result.redirect.indexOf( "https://" ) != -1 || result.redirect.indexOf( "http://" ) != -1 ) {
redirectUrl = result.redirect;
} else {
redirectUrl = decodeURI( result.redirect );
}
jQuery.get(redirectUrl, function(data){
var newBodyString = data.replace(/^[\S\s]*<body[^>]*?>/i, "").replace(/<\/body[\S\s]*jQuery/i, "");
var newBody = jQuery("<div></div>").html(newBodyString);
if(newBody.find('.wgm-go-back-button').length > 0){
jQuery('body').html(newBody.html());
jQuery('form.checkout').append(additionalFields);
jQuery('form.checkout').append('<input type="hidden" name="ogonecw_payment_method_choice" value="'+selectedPaymentMethod+'"/>');
jQuery('.wgm-go-back-button').on('click', function() {
jQuery('form.checkout').append('<input type="hidden" name="cw-wgm-button-back" value="back"/>');
});
jQuery('form.checkout').on('submit', function(){
return CheckoutObject.placeOrder();
});
jQuery("html, body").animate({
scrollTop: jQuery("form.checkout").offset().top - 100
}, 1e3);
}
else {
window.location = decodeURI( redirectUrl );
}
});
}
else if(typeof result.ajaxScriptUrl !== 'undefined'){
jQuery.getScript(result.ajaxScriptUrl, function() {
eval("var callbackFunction = " + result.submitCallbackFunction);
callbackFunction(getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase()));
});
}
else {
var newForm = '<form id="ogonecw_preview_form" action="' + result.form_action_url + '" method="POST">';
newForm += result.hidden_form_fields;
newForm += generateHiddenFields(getFormFieldValues('ogonecw-preview-fields', selectedPaymentMethod.toLowerCase()));
newForm += '</form>';
jQuery('body').append(newForm);
jQuery('#ogonecw_preview_form').submit();
}
}
});
So what exactly is causing this error since the plugin seems to be setup correctly
Im getting Uncaught TypeError: Cannot use 'in' operator to search for 'length' in on a autocomplete field. This is the code:
enable_autocomplete: function() {
$( 'input.fm-autocomplete:visible' ).each( function() {
if ( !$( this ).hasClass( 'fm-autocomplete-enabled' ) ) {
var ac_params = {};
var $el = $( this );
var $hidden = $el.siblings( 'input[type=hidden]' ).first();
ac_params.select = function( e, ui ) {
e.preventDefault();
$el.val( ui.item.label );
$hidden.val( ui.item.value ).trigger( 'change' );
};
ac_params.focus = function( e, ui ) {
e.preventDefault();
$el.val( ui.item.label );
}
if ( $el.data( 'action' ) ) {
ac_params.source = function( request, response ) {
// Check for custom args
var custom_args_js_event = $el.data( 'customArgsJsEvent' );
var custom_data = '';
if ( 'undefined' !== typeof custom_args_js_event && null !== custom_args_js_event ) {
var custom_result = $el.triggerHandler( custom_args_js_event );
if ( 'undefined' !== typeof custom_result && null !== custom_result ) {
custom_data = custom_result;
}
}
$.post( ajaxurl, {
action: $el.data( 'action' ),
fm_context: $el.data( 'context' ),
fm_subcontext: $el.data( 'subcontext' ),
fm_autocomplete_search: request.term,
fm_search_nonce: fm_search.nonce,
fm_custom_args: custom_data
}, function( result ) {
console.log( result );
$.parseJSON( response( result ) );
} );
};
All other questions related to this error suggested a $.parseJSON but it's not working for me. This is the console.log of result when i type eco:
[{"label":"Economy Talks","value":1480},{"label":"Economy","value":212},{"label":"Economy motors","value":2038},{"label":"Telecomunica\u00e7\u00f5es","value":402}]
Console.log of response:
function (){return a.apply(b||this,c.concat(e.call(arguments)))}
It finds the right suggestions but then i get Uncaught TypeError: Cannot use 'in' operator to search for 'length' in and i'm not able to select any option. Any ideas how to fix this?
I'm using this code (http://technologymantrablog.com/dynamic-combobox-ajax-php-mysql/) for getting country/state/city from my database to php/html selects. It's working perfect in registration form. Everything is fine! The problem is, after user register at the system, he can try to edit your registration/profile. Then, the select for country/state/city appears again. And there is the problem. If I use the same ID's from javascript it won't work. If I try to change the ID's and change the javascript, won't work too. Calling two functions and two different files, won't work too.
getSelects.php
function getStatus() {
if (window.XMLHttpRequest) {
xmlhttp3 = new XMLHttpRequest();
} else {
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("inputStatus").innerHTML=xmlhttp3.responseText;
}
}
xmlhttp3.open("GET","includes/getStatus.php",true);
xmlhttp3.send();
}
function getMotivo(statusID) {
if (window.XMLHttpRequest) {
xmlhttp3 = new XMLHttpRequest();
} else {
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("inputMotivo").innerHTML=xmlhttp3.responseText;
}
}
xmlhttp3.open("GET","includes/getMotivo.php?statusID="+statusID,true);
xmlhttp3.send();
}
function getComplemento(motivoID) {
if (window.XMLHttpRequest) {
xmlhttp3 = new XMLHttpRequest();
} else {
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("inputComplemento").innerHTML=xmlhttp3.responseText;
}
}
xmlhttp3.open("GET","includes/getComplemento.php?motivoID="+motivoID,true);
xmlhttp3.send();
}
INCLUDES
Status:
echo '<select onchange="getMotivo(this.value);" class="form-control" name="status" id="status">';
echo
'<option value="">-- Selecione --</option>
<option value="0">Bloqueado</option>
<option value="1">Ativo</option>';
echo'</select>';
Motivo:
include("../lib/conexao.php");
$statusID = $_GET['statusID'];
echo '<select onchange="getComplemento(this.value);" class="form-control" name="motivo" id="motivo">';
echo '<option value="" selected>-- Selecione um Motivo --</option>';
$q = "SELECT * FROM motivo WHERE status = '$statusID' AND tipo = 'C' ORDER BY motivo";
if($res = $con->query($q))
{
while($obj = $res->fetch_object())
{
echo'<option value="'. $obj->motivoID .'">'. $obj->motivo .'</option>';
}
}
echo'</select>';
Complemento:
include("../lib/conexao.php");
$motivoID = $_GET['motivoID'];
if($motivoID == 2 || $motivoID == 4 || $motivoID == 5 || $motivoID == 6 || $motivoID == 8 || $motivoID == 9) {
echo '<label for="complemento">Complemento</label>';
echo '<input type="text" name="complemento" class="form-control" id="complemento" placeholder="Insira o Complemento">';
}
header.php:
<script>
function init() {
getStatus();
}
</script>
</head>
<body onload="init();">
I think if I post all the code files here will be very long post. But, with my text in the first paragraph I think I could explain what I'm trying to do.
I don't know if this will help solve your problem ( hope it does ) but I mentioned using a more or less generic ajax function and using that for the bulk of your work so this is what I meant.
function _ajax( url, options ){
var factories=[
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.4.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.5.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.6.0'); },
function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
];
/* Try each factory until we have a winner */
for( var i=0; i < factories.length; i++ ) {
try { var req = factories[ i ](); if( req!=null ) { break; } }
catch( err ) { continue; }
};
var method=options.hasOwnProperty('method') ? options.method.toUpperCase() : 'POST';
var callback=options.hasOwnProperty('callback') ? options.callback :false;
if( !callback ){
alert( 'No callback function assigned - a callback is required to handle the response data' );
return false;
}
var headers={
'Accept': "text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8",
'Content-type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
/* The main parameters of the request */
var params=[];
if( options.hasOwnProperty('params') && typeof( options.params )=='object' ){
for( var n in options.params ) params.push( n + '=' + options.params[n] );
}
/* Additional arguments that can be passed to the callback function */
var args=options.hasOwnProperty('args') ? options.args : options;
/* Assign callback to handle response */
req.onreadystatechange=function(){
if( req.readyState==4 ) {
if( req.status==200 ) options.callback.call( this, req.response, args );
else console.warn( 'Error: '+req.status+' status code returned' );
}
}
/* Execute the request according to desired method: other methods could be added here */
switch( method ){
case 'POST':
req.open( method, url, true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( params.join('&') );
break;
case 'GET':
req.open( method, url+'?'+params.join('&'), true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( null );
break;
}
}
/*
example usage:
--------------
*/
function getStatus() {
_ajax.call( this, '/includes/getStatus.php',{ callback:cb_ajax, method:'get', args:{ id:'inputStatus' } } );
}
function getMotivo( statusID ) {
_ajax.call( this, '/includes/getMotivo.php',{ callback:cb_ajax, method:'get', params:{ 'statusID':statusID }, args:{ id:'inputMotivo' } } );
}
function getComplemento( motivoID ) {
_ajax.call( this, '/includes/getMotivo.php',{ callback:cb_ajax, method:'get', params:{ 'motivoID':motivoID }, args:{ id:'inputComplemento' } } );
}
/* The callback function */
function cb_ajax( r, o ){
console.info( 'ajax response: %s, args: %s', r, o );
if( o.hasOwnProperty( 'id' ) && document.getElementById( o.id ) ) document.getElementById( o.id ).innerHTML=r;
}
html form
---------
<form name='so_test_motivo' method='post' action='/test/target.php' enctype="multipart/form-data">
<select name='country' onchange='getStatus()'>
<option value=0 selected> Choose an option
<option value=1> Test
</select>
<select id='inputStatus' name='inputStatus' onchange='getMotivo(this.value)'>
</select>
<select id='inputMotivo' name='inputMotivo' onchange='getComplemento(this.value)'>
</select>
<select id='inputComplemento' name='inputComplemento'>
</select>
</form>
And for the purposes of the test, the php script /test/target.php was simply sending dummy data back like this:
$id=$_GET['id'];
for( $i=0; $i < 50; $i++ ) echo '<option value='.( ( $i+1 ) + $id ).'>Option - '.( ( $i+1 ) + $id ).PHP_EOL;
I am trying to get stylesheet_directory in JS, but can't get it to work.
Here is what I have tried:
url : '<?php bloginfo('stylesheet_directory'); ?>/img/hamburger.svg'
AND:
var stylesheetDir = "<?php bloginfo('stylesheet_directory') ?>";
url : '$stylesheetDir/img/hamburger.svg',
I guess there is just a problem with some characters or something? Could you please help me out?
svgicons-config-js
var stylesheetDir = "<?php bloginfo('stylesheet_directory') ?>";
url == $stylesheetDir;
decodeURI(url);
var svgIconConfig = {
hamburgerCross : {
url : stylesheetDir + '/img/hamburger.svg',
animation : [
{
el : 'path:nth-child(1)',
animProperties : {
from : { val : '{"path" : "m 5.0916789,20.818994 53.8166421,0"}' },
to : { val : '{"path" : "M 12.972944,50.936147 51.027056,12.882035"}' }
}
},
{
el : 'path:nth-child(2)',
animProperties : {
from : { val : '{"transform" : "s1 1", "opacity" : 1}', before : '{"transform" : "s0 0"}' },
to : { val : '{"opacity" : 0}' }
}
},
{
el : 'path:nth-child(3)',
animProperties : {
from : { val : '{"path" : "m 5.0916788,42.95698 53.8166422,0"}' },
to : { val : '{"path" : "M 12.972944,12.882035 51.027056,50.936147"}' }
}
}
]
},
};
hamburger_animation.js
(function() {
[].slice.call( document.querySelectorAll( '.si-icons-default > .si-icon' ) ).forEach( function( el ) {
var svgicon = new svgIcon( el, svgIconConfig );
} );
new svgIcon( document.querySelector( '.si-icons-easing .si-icon-hamburger' ), svgIconConfig, { easing : mina.backin } );
new svgIcon( document.querySelector( '.si-icons-easing .si-icon-hamburger-cross' ), svgIconConfig, { easing : mina.elastic, speed: 600 } );
})();
svgicons.js
/**
* svgicons.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2013, Codrops
* http://www.codrops.com
*/
;( function( window ) {
'use strict';
/*** helper functions ***/
// from https://github.com/desandro/classie/blob/master/classie.js
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
function hasClass( el, c ) {
return 'classList' in document.documentElement ? el.classList.contains( c ) : classReg( c ).test( el.className )
}
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
// from http://stackoverflow.com/a/11381730/989439
function mobilecheck() {
var check = false;
(function(a){if(/(android|ipad|playbook|silk|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
return check;
}
// http://snipplr.com/view.php?codeview&id=5259
function isMouseLeaveOrEnter( e, handler ) {
if (e.type != 'mouseout' && e.type != 'mouseover') return false;
var reltg = e.relatedTarget ? e.relatedTarget :
e.type == 'mouseout' ? e.toElement : e.fromElement;
while (reltg && reltg != handler) reltg = reltg.parentNode;
return (reltg != handler);
}
/*** svgIcon ***/
function svgIcon( el, config, options ) {
this.el = el;
this.options = extend( {}, this.options );
extend( this.options, options );
this.svg = Snap( this.options.size.w, this.options.size.h );
this.svg.attr( 'viewBox', '0 0 64 64' );
this.el.appendChild( this.svg.node );
// state
this.toggled = false;
// click event (if mobile use touchstart)
this.clickevent = mobilecheck() ? 'touchstart' : 'click';
// icons configuration
this.config = config[ this.el.getAttribute( 'data-icon-name' ) ];
// reverse?
if( hasClass( this.el, 'si-icon-reverse' ) ) {
this.reverse = true;
}
if( !this.config ) return;
var self = this;
// load external svg
Snap.load( this.config.url, function (f) {
var g = f.select( 'g' );
self.svg.append( g );
self.options.onLoad();
self._initEvents();
if( self.reverse ) {
self.toggle();
}
});
}
svgIcon.prototype.options = {
speed : 200,
easing : mina.linear,
evtoggle : 'click', // click || mouseover
size : { w : 64, h : 64 },
onLoad : function() { return false; },
onToggle : function() { return false; }
};
svgIcon.prototype._initEvents = function() {
var self = this, toggleFn = function( ev ) {
if( ( ( ev.type.toLowerCase() === 'mouseover' || ev.type.toLowerCase() === 'mouseout' ) && isMouseLeaveOrEnter( ev, this ) ) || ev.type.toLowerCase() === self.clickevent ) {
self.toggle(true);
self.options.onToggle();
}
};
if( this.options.evtoggle === 'mouseover' ) {
this.el.addEventListener( 'mouseover', toggleFn );
this.el.addEventListener( 'mouseout', toggleFn );
}
else {
this.el.addEventListener( this.clickevent, toggleFn );
}
};
svgIcon.prototype.toggle = function( motion ) {
if( !this.config.animation ) return;
var self = this;
for( var i = 0, len = this.config.animation.length; i < len; ++i ) {
var a = this.config.animation[ i ],
el = this.svg.select( a.el ),
animProp = this.toggled ? a.animProperties.from : a.animProperties.to,
val = animProp.val,
timeout = motion && animProp.delayFactor ? animProp.delayFactor : 0;
if( animProp.before ) {
el.attr( JSON.parse( animProp.before ) );
}
if( motion ) {
setTimeout(function( el, val, animProp ) {
return function() { el.animate( JSON.parse( val ), self.options.speed, self.options.easing, function() {
if( animProp.after ) {
this.attr( JSON.parse( animProp.after ) );
}
if( animProp.animAfter ) {
this.animate( JSON.parse( animProp.animAfter ), self.options.speed, self.options.easing );
}
} ); };
}( el, val, animProp ), timeout * self.options.speed );
}
else {
el.attr( JSON.parse( val ) );
}
}
this.toggled = !this.toggled;
};
// add to global namespace
window.svgIcon = svgIcon;
})( window );
The site can be found here: http://goo.gl/wuUwUG
Please inspect element (or similar), and look at the code where it says "Failed to load resource: the server responded with a status of 404 (Not Found)"
Instead of:
url : '$stylesheetDir/img/hamburger.svg',
use
url : stylesheetDir + '/img/hamburger.svg',
EDIT
So, the following code is obsolete and unnecessary (it does nothing and can be removed):
url == $stylesheetDir;
decodeURI(url);
Feel free to remove it. Other than that everything looks fine.
I guess some more code is needed. You should reveal how you're using the svgIconConfig variable, and specifically, the url property.
EDIT
Thanks for revealing some more code. It appears that you're calling a <?php ... ?> block within a JS file. This block is not parsed by the server, so it is directly displayed instead of rendering the URL to the theme.
I'm not sure how you're enqueueing the scripts in the code, so I'll propose a solution that will work with any use case.
To fix this, insert the following in your theme functions.php
add_action('wp_head', 'my_js_var_stylesheet_directory', 9);
function my_js_var_stylesheet_directory() {
echo '<script type="text/javascript">';
echo 'var stylesheetDir = "' . get_bloginfo('stylesheet_directory') . '"';
echo '</script>';
}
and delete the top 3 lines from your svgicons-config-js file, as they are unnecessary.
From your code you have to echo the path for the css directory.
Check this one out :
var stylesheetDir = '<?php echo loginfo('stylesheet_directory') ; ?>/img/hamburger.svg';
console.log(stylesheetDir);