Thanks to give me the advise to work with JSON.
I Think i get it now.
Perhaps someone could look over it?
Here My Code
Button:
<div id="div3">
<button id="rob-wp-ajax-vorlage-button">ok</button>
</div>
My PHP Code
function load_my_ajax_vorlage()
{
wp_enqueue_script( 'my_custom_js', plugins_url( 'ajax-vorlage-script.js', __FILE__ ), array('jquery'), false, false );
}
add_action('wp_enqueue_scripts', 'load_my_ajax_vorlage');
add_action( 'wp_footer', 'load_my_ajax_vorlage' );
add_action('wp_enqueue_scripts', 'example_localize_ajax');
function example_localize_ajax(){
wp_localize_script('jquery', 'ajax', array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('example_ajax_nonce'),
));
}
//Example AJAX Function
add_action('wp_ajax_example_function', 'example_function');
add_action('wp_ajax_nopriv_example_function', 'example_function');
function example_function(){
$var1 = "value1";
$var2 = "value2";
echo json_encode(array($var1, $var2));
wp_die(); // this is required to terminate immediately and return a proper response:- https://codex.wordpress.org/AJAX_in_Plugins
}
my JS
var ajaxurl="<?php echo admin_url("admin-ajax.php") ?>";
jQuery(document).ready(function($) {
$( '#rob-wp-ajax-vorlage-button' ).click( function() {
jQuery.ajax({
type: "POST",
url: ajax.url,
dateType: 'JSON',
data: {
nonce: ajax.nonce,
action: 'example_function',
data: {
//firstname: 'fname',
//lastname: 'lname'
},
},
success: function(response){
console.log('Successful AJAX Call! /// Return Data: ' + response);
var result = $.parseJSON(response);
console.log('result0 ' + result[0]);
console.log('result1 ' + result[1]);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log('ERROR AJAX Call! /// Return Data: ' + XMLHttpRequest);
},
timeout: 60000
});
return false;
});
});
I Delete the scentence with the PDF i think you are right.
I will have a Look in REST API…
is this the right way?
Thx Rob