I need to append some php code, when user click in sample button, my code works properly, but I need do my job cleaner. I've searched and I found out, I should be using jquery ajax for this, but I don't know what should to do with ajax. I read some articles about jquery ajax, and I found some functions, like $.ajax()
, $.get()
, $.post()
but I dont know really what to do? can someone say me, what I should to do
button.live( 'click', function(){
sample.append(<?phpcodes?>);
});
append(
'<?php echo get_template_directory_uri(); ?>'+
'<?php foreach ( $terms as $term ){ echo '<option value="'. $term->slug .'">'. $term->name .'</option>'; } ?>'+
'<?php echo __( "Sample","textDomain" ); ?>'+
'<?php echo $example[0]['options']['0']['id']; ?>'+
'and more ...'
);
You should put the PHP code in a separate .php file and call that file with JavaScript (ajax) when the user clicks the button. When the file is called the php functions in that file will execute.
Examlple HTML
<div id="mybutton">My button</div>
<div id="result">My result</div>
Example JavaScript
$( "#mybutton" ).on( "click", function() {
$( "#result" ).load( "myphpcode.php", function() {
});
});
Example myphpcode.php
<?php
// Do your cleaning here
echo 'Done cleaning!';
?>