Last active
November 9, 2017 12:38
-
-
Save axxe16/a0147938aeea254eb0c1ea13465b8e41 to your computer and use it in GitHub Desktop.
procedura per l'utlizzo di uno script ajax in frontend su Wordpress #ajax #wp #js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
$('#form_tesseramento #ek_province').on('change', function(){ | |
var provincia_id = $(this).val(); | |
console.log(provincia_id); | |
jQuery.ajax({ | |
url : postdata.ajax_url, //definito riga 8 precedente script | |
type : 'post', | |
data : { | |
action : 'ek_skipay_getComuneByProvincia', //function ajax da richiamare | |
provincia_id : provincia_id //dato da passare, in questo caso id estratto da option selezionata | |
}, | |
success : function( data ) { | |
$('#form_tesseramento #ek_comuni > option').remove(); | |
$.each(data, function(index, element) { | |
$('#form_tesseramento #ek_comuni').append('<option value="'+ element.id +'">' + element.nome + '</option>'); | |
}); | |
$('#form_tesseramento #ek_comuni').prop('disabled', false); | |
$('#form_tesseramento #ek_comuni').selectpicker('refresh'); | |
} | |
}); | |
}); | |
}) ( jQuery ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//aggiungo lo script js e definisco ajax url | |
add_action( 'wp_enqueue_scripts', 'ajax_enqueue_scripts' ); | |
function ajax_enqueue_scripts() { | |
wp_enqueue_script( 'ajaxscript', plugins_url( '../ek_js/ajaxScript.js', __FILE__ ), array('jquery'), '1.0', true ); | |
//definisco ajax url usando localize | |
wp_localize_script( 'ajaxscript', 'postdata', array( | |
'ajax_url' => admin_url( 'admin-ajax.php' ) | |
)); | |
} | |
//aggiungo funzione ek_skipay_getComuneByProvincia per utenti loggati e non | |
//wp_ajax_nopriv_ e wp_ajax_ + il nome della funzione da chiamare via ajax | |
add_action( 'wp_ajax_nopriv_ek_skipay_getComuneByProvincia', 'ek_skipay_getComuneByProvincia' ); | |
add_action( 'wp_ajax_ek_skipay_getComuneByProvincia', 'ek_skipay_getComuneByProvincia' ); | |
//query alla tabella comuni chiamata via ajax | |
function ek_skipay_getComuneByProvincia() { | |
global $wpdb; | |
$comuni_query = 'select * from `' . $wpdb->get_blog_prefix() . 'ek_skipay_comuni` WHERE `id_provincia` = '. $_POST['provincia_id'] .' ORDER by `nome` ASC'; | |
$comuni_items = $wpdb->get_results( $comuni_query, ARRAY_A ); | |
//genero json con comuni in provincia | |
header('Content-Type: application/json'); | |
echo json_encode( $comuni_items ); | |
die(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment