Created
August 22, 2017 16:40
-
-
Save deryckoe/8152671fab87be77ed6fceec3c323ef8 to your computer and use it in GitHub Desktop.
Form ajax
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 | |
add_action( 'admin_footer', 'submit_javascript' ); | |
// Imprime JS el el html del admin. | |
function submit_javascript() { ?> | |
<script type="text/javascript" > | |
jQuery(document).ready(function($) { | |
$('#idForm').on( 'submit', function(e) { | |
e.preventDefault(); // evita el submit convencional | |
// serializa todos los campos del formulario, debes incluir un campo action con valor value="my_action". | |
// es importante porque ese action es que el activa la funcion de lado admin en WP. | |
var data = $(this).serialize(); | |
// desde verison 2.8 ajaxurl ya esta definida por defecto asi que solo ponla debajo y listo. | |
jQuery.post(ajaxurl, data, function(response) { | |
// response tiene el contenido generado en la funcion, con JS puedes agregar nuevo HTML debajo del fomulario, justo lo que buscas. | |
alert('Got this from the server: ' + response); | |
}); | |
}); | |
}); | |
</script> <?php | |
} | |
add_action( 'wp_ajax_my_action', 'my_action' ); | |
// Esta funcion responde a la llamada de AJAX y aqui haces lo que necesites hacer. Devuelves el valor al navegador utilizando echo, al final. | |
function my_action() { | |
$variable_post_ejemplo = $_POST['un valor que viene del formulario'] ); | |
echo $variable_post_ejemplo; | |
wp_die(); // esto siempre al final de la funcion, para que termine ahi. IMPORTANTE. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment