I have this js in /js/functions.js:
jQuery(document).ready( function($){
//Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
$.ajax({
url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
type: 'POST',
data:{
action: 'myaction', // this is the function in your functions.php that will be triggered
name: 'John',
age: '38'
},
success: function( data ){
//Do something with the result from server
console.log( data );
}
});
});
And in functions.php I have:
<?php
add_action( 'wp_enqueue_scripts', 'so18550905_enqueue_scripts' );
function so18550905_enqueue_scripts(){
wp_register_script( 'ajaxHandle', get_template_directory_uri() . '/js/functions.js', array(), false, true );
wp_enqueue_script( 'ajaxHandle' );
wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_ajax_nopriv_myaction', 'so18550905_wp_ajax_function' );
function so18550905_wp_ajax_function(){
//DO whatever you want with data posted
//To send back a response you have to echo the result!
echo $_POST['name'];
echo $_POST['age'];
wp_die(); // ajax call must die to avoid trailing 0 in your response
}
?>
But I can't echo name and age on front pages.
Where is the problem?
Thanks.
AJAX
is happening on admin side, not client-facing side, in background.return
it