Last active
June 9, 2017 22:14
-
-
Save agustinprosperi/4aa5a6f5b6b76de8077c0c4da44e1071 to your computer and use it in GitHub Desktop.
wordpress ajax callback example
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
<form id="search"> | |
<input type="hidden" name="action" value="custom_search" /> | |
<input type="text" id="texto" name="texto" /> | |
<input type="submit" value="submit" /> | |
</form> | |
<div id="answer"></div> | |
<script type="text/javascript"> | |
jQuery(function($){ | |
$("#search").submit(function(e){ | |
if( $("#search").hasClass("sending") ) return false; | |
// if no sending yet, send | |
e.preventDefault(); | |
// creamos un objeto con los inputs del form {name:value,...} | |
var formData = $("#search").serialize(); | |
$("#search").addClass("sending"); | |
$.ajax({ | |
type: 'POST', | |
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>', | |
data: formData, | |
success: function(data, textStatus, jqXHR){ | |
$("#answer").html( data ); | |
}, | |
error: function(jqXHR, textStatus, errorThrown){ | |
$("#answer").html('ERROR'); | |
$("#search").removeClass("sending"); | |
} | |
}); | |
}); | |
}); | |
</script> | |
<?php | |
/**********esto*va*en*tu*functions.php**********/ | |
add_action( 'wp_ajax_custom_search', 'custom_search_callback' ); | |
add_action( 'wp_ajax_nopriv_custom_search', 'custom_search_callback' ); | |
function custom_search_callback(){ | |
$texto = sanitize_text_field($_REQUEST['texto']); | |
if( !empty($texto) ){ | |
$taxonomy_arr = get_terms( 'taxonomy', array( | |
'hide_empty' => 0, | |
'order'=>'ASC', | |
'search' => $texto | |
) ); | |
//var_dump( $cats_number ); | |
foreach ($taxonomy_arr as $key => $taxonomy): | |
?> | |
<div><?php echo $taxonomy->name; ?></div> | |
<?php | |
endforeach | |
}else{ | |
?> | |
<div>Vacia</div> | |
<?php | |
} | |
exit(); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment